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!