Let's say I have an object Foo. I also have an FooBuilder which is to be used to construct the Foo objects. When and where should I validate the Foo object's data?
Foo foo = new FooBuilder()
.withX("specific data for X")
.withY("specific data for Y")
.build();
Let's add to the equation that the validation may contain lookups in for example a database. Should the builder perform a validation inside the build method? Or should there be a specific validate method in the foo object? Or maybe the validation is best off completely abstracted from both the Foo object and the FooBuilder?
Ideally it should not be possible to create an invalid Foo
object at all. Therefore having a validation method in Foo
is not the best choice.
The validation should be done as early as possible. This could be in the build()
method or - if possible - even earlier within the setter methods of the builder.
If you should put the actual implementation of your validator into the builder or into a separate class depends its complexity. If it requires things like database lookups, as you mentioned, it probably makes sense to create a separate validation class.
I like to add that the builder is sometimes considered an antipattern indicating that the class is probably too complex and should be split into multiple smaller classes.