Reputation: 1759
According to the book Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, and Vlissides:
Intent: separate the construction of a complex object from its representation so that the same construction process can create different representations.
In general, the Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final object.
With the builder pattern, we have a build method to generate an object which is immutable.
My Question:
Can I use the builder pattern while also keeping setter methods in the class of the generated object, allowing the possibility to mutate the built object?
If I produce mutable objects, should I not use the builder pattern?
Upvotes: 5
Views: 3829
Reputation: 1042
The Builder Pattern is meant to replace what are called telescoping constructors (with a nod to @scottb) for optional parameters and not much else. It does not require the object to be immutable.
Also the builder should generally only include the attributes that matter at construction (a.k.a. build) time, hence the name builder. It should not include attributes that change over the life of the object but don't really matter after construction.
Conceptually, if you have a builder for Child
, the only 3 things that will matter are the mom
, the dad
and childGenes
(boy/girl, other genetic material). The height or weight of the child should not be a part of the builder as it will be driven partially by genes but will constantly change by factors beyond those present at birth (or "build" time).
That said, unless you really need it, it's best to have the object immutable.
Hope that helps!
Upvotes: 11
Reputation: 10084
There is value in the Builder Pattern than goes beyond just helping to solve the telescoping parameter problem.
Builders are especially useful for constructing immutable objects because, for such objects, all the data must be supplied at build time. When there is a large amount of data to supply or when multiple steps must be completed, the Builder Pattern is pretty easy to recommend.
There is no rule that builder objects can't build mutable objects, however for mutable objects the JavaBeans pattern provides the same benefits (easy readability, self-documentation, reduced error prone-ness) with less code.
Upvotes: 8