Validation of an object is an integral part of creating an object using collectors. Although you can have a separate procedure that performs verification, this separation is not required: the verification code can be part of the function that performs the assembly. In other words, you can do it
TargetObject build() {
TargetObject res = new TargetObject();
res.setProperty1();
res.setProperty2();
validate(res);
return res;
}
void validate(TargetObject obj) {
if (...) {
throw new IllegalStateException();
}
}
or that:
TargetObject build() {
TargetObject res = new TargetObject();
res.setProperty1();
res.setProperty2();
if (...) {
throw new IllegalStateException();
}
return res;
}
It is important that validation occurs after, and not earlier, the construction of the target object. In other words, you need to check the state of the object, not the state of the builder.
source
share