1

I have designed a simple objects validation framework in Java in the context of a code refactoring.

The framework has a ValidationRule interface with one method Errors validate(MyObject myObject, Context ctx). There are a number of classes (Validators) implementing different validation rules, each validation checking a different part of the object properties and children collections.

The rules are executed in a loop and validation errors accumulated and returned to the user.

Now, the code that I'm refactoring is often modifying the object under validation in the "middle" of some validation logic:

if (myObject.getName() == null) {
    myObject.setName(DEFAULT_NAME);
}

Certain rules rely on the assumption that the object has been modified (so, for instance, they expect the name to be always not null).

From a design perspective, I would like to keep the validation framework "read-only". This makes the rules simple to understand and reason about,but I need to be able to mutate certain object's properties from a rule to the next.

What would be a good pattern to achieve such a result?

1) validation rules do not mutate the object under validation (this can be enforced by passing an ImmutableMyObject to the validation interface)

2) each rule should be able to mutate the objects under validation in order for the next rules to function

Ideas welcome!

3

My expectation of a chain of validation rules is that if I remove a passing rule or if I reorder the chain of rules, then the final outcome of the validation remains the same.

That means that the validation rules must not depend on actions done by an earlier rule in the chain and that can easiest be guaranteed by treating the object under validation as immutable.

If some validation rules require that certain properties are non-null, then that should be arranged before passing the object to the chain of rules.
If some validation rules expect property A to have value X and other rules expect that property to have value Y, then it is not expected that an object passes validation if both those rules are present in the chain.

| improve this answer | |
  • Yes, I agree. This gives the additional benefits to be able to run the validation rules in parallel, since they do not depends on each other. According to your answer, the best approach is to create a "pre-processor" of sort that prepares the data, prior to validation. – Luciano Fiandesio Apr 4 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.