Source Code : Validation using the builder pattern

Validation using the builder pattern

public class PersonValidator {

private static final int MAX_SEQUENCE = 20;

private final List exceptions;

private PersonValidator(final Validator validator) {

exceptions = new ArrayList(validator.exceptionsOccured);

}

public boolean hasException() {

return exceptions.isEmpty();

}

public List getAllExceptions() {

return exceptions;

}

public String getAllExceptionsFormatted() {

//

}

public void throwFirstExceptionIfAny() throws BaseException {

if (!exceptions.isEmpty()) {

throw exceptions.get(0);

}

}

public static class Validator {

private final List exceptionsOccured = new ArrayList();

public Validator isNullDoThrow(final Person person) throws BaseException {

if (person == null) {

throw new BaseException("Person must not be null");

}

return this;

}

public Validator code(final String code) {

if (StringUtils.isBlank(code)) {

exceptionsOccured.add(new ValidationException("Code must not be empty"));

}

return this;

}

public Validator sequence(final int sequence) {

if (sequence >= MAX_SEQUENCE) {

exceptionsOccured.add(new ValidationException("Sequence must be smaller than " + MAX_SEQUENCE));

}

return this;

}

@SuppressWarnings("synthetic-access")

public PersonValidator validate() {

return new PersonValidator(this);

}

}

}

You can use it like this:

PersonValidator personValidator = new Validator().code("11111")
  .sequence(2).validate();
personValidator.throwFirstExceptionIfAny();
or some steps at a time:

Validator validator = new Validator();
validator.code("11111");
 
// do some other stuff
 
validator.sequence(2);
PersonValidator person = validator.validate();
if(person.hasException()) {
  person.getAllExceptionsFormatted()
}