Source Code : Validation using the builder pattern

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()

}

Validation using the builder pattern

I currently have a little crush in the builder pattern. This pattern and variations of it can solve common programming issues in a pretty straightforward way. I will give you an example of how you can use it in a validation context. A use case could be when you want to be able to perform different operations on the validation result. And you want a clean separation between the actual validation logic and the result of the validation. An advantage is that it is much less error prone e.g how to use the objects compared to letting a single class have all responsibility. Further it also makes it possible to have different “validation result objects” for the same validation logic, if needed.

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);

}

}

}