I have searched very hard on google on every possible discussion forum about this topic but I can't seem to find anything that meets my needs. I try to explain what I want to obtain: basically I want to use the something similar to the builder pattern to validate the state of an object in creation phase because this allows me to centralize the validation logic in an elegant way and it is readable and easy to mantain by a developer. For example such a code:
Person person = new PersonBuilder() .id(1)
.name("John")
.surname("Smith")
.age(36)
.hobbies("Playing tennis") .build();
for me is very elegant and readable and it is perfect because everytime that I want to use an object of the Person class I can provide only valid state of object before stepping through the next phases.
But to think about it this validation rules are good only for an object for which I want to perform an insert or update because the validator checks that all mandatory fields are setted otherwise throws back an IllegalStateExcpetion. What if I want to perform a research of the person by any of the available attributes? I mean when I search for an object I don't have to specific all the mandatory fields. I could also specify just the surname or just one of the other available fields...
Could it be acceptable to add a "buildForSearch" method into the builder with different criteria of validation?
I know that maybe is conceptually wrong to differentiate the entity behaviour of validation basing on the actions but do you know if there is a pattern to accomplish this, mantaining the advantages of the builder pattern?
Many thanks for the help
Aucun commentaire:
Enregistrer un commentaire