Reputation: 22171
Suppose a Car
model object (as case class
), immutable and created using builder pattern. (Builder pattern by Joshua Bloch).
Its build
method calls a CarValidator
object in order to allow creation or not of the concerned Car
. Otherwise, it throws an IllegalStateException
with unexpected fields precised.
Thus, no one could create a stale or invalid Car
at any time at Runtime, great!
Suppose now a web form to create a Car
. Play's controller would contain this form mapping:
val carForm = Form( //this is a conceptual sample
mapping(
"brand" -> nonEmptyText,
"description" -> nonEmptyText,
"maxSpeed" -> number
"complexElement" -> number.verifying(........) //redundant validation here
)(Car.apply)(Car.unapply)
)
In this example, there are some basics fields, but imagine more complex fields demanding complex business validations like the complexeElement
here.
I really have the feeling that I would easily break the DRY(Don't Repeat Yourself).
Indeed, whatever the form validation would bring, this would be already provided by my Car
builder's validator, since validation on model is THE most important validation place and shouldn't depend on anything else.
I imagine a solution with a Helper
class near my Controller
dealing with the same validator object that my builder uses. However, it forces me to get all validation methods public
in order to be called independently at any validation step of my web form (like in the code snippet above).
What would be a good practice to keep this builder principle while avoiding breaking DRY?
Upvotes: 1
Views: 266
Reputation: 11244
If you want to keep the builder pattern, you should not have Form
create instances. The form should just make sure the information that comes in is of the correct type. The form can not create the final Car
because it does not know the rules to make a Car
, the builder does.
So I would say you let the form put stuff into an intermediary object (a tuple or PossibleCar
case class) and build your Car
(using the builder) with that object.
There is another route available, but that means that you must create (possibly complex) structures that let's you adapt the different types of validation. Both the builder and form can then use these validations (with the help of adapters) to create valid cars. I don't know enough about the situation you're in to give you advise on which route to take.
Upvotes: 2