A Dive into the Builder Pattern
Join the DZone community and get the full member experience.
Join For FreeThe Builder pattern has been described in the Gang of Four “Design Patterns” book:
The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.
A common implementation of using the Builder pattern is to have a fluent interface, with the following caller code:
Person person = new PersonBuilder().withFirstName("John").withLastName("Doe") .withTitle(Title.MR).build();This code snippet can be enabled by the following builder:
public class PersonBuilder { private Person person = new Person(); public PersonBuilder withFirstName(String firstName) { person.setFirstName(firstName); return this; } // Other methods along the same model // ... public Person build() { return person; } }
The job of the Builder is achieved: the Person
instance is well-encapsulated and only the build()
method finally returns the built instance. This is usually where most articles stop, pretending to have covered the subject. Unfortunately, some cases may arise that need deeper work.
Let’s say we need some validation handling the final Person
instance, e.g. the lastName
attribute is to be mandatory. To provide this, we could easily check if the attribute is null
in the build()
method and throws an exception accordingly.
public Person build() { if (lastName == null) { throw new IllegalStateException("Last name cannot be null"); } return person; }
Person person1 = new PersonBuilder().withFirstName("John").withLastName("Doe").withTitle(Title.MR).build(); // OK Person person2 = new PersonBuilder().withFirstName("John").withTitle(Title.MR).build(); // Doesn't compile
We have to update our builder so that it may either return itself, or an invalid builder that lacks the build()
method as in the following diagram. Note the first PersonBuilder
class is kept as the entry-point for the calling code doesn’t have to cope with Valid-
/InvaliPersonBuilder
if it doesn’t want to.
This may translate into the following code:
public class PersonBuilder { private Person person = new Person(); public InvalidPersonBuilder withFirstName(String firstName) { person.setFirstName(firstName); return new InvalidPersonBuilder(person); } public ValidPersonBuilder withLastName(String lastName) { person.setLastName(lastName); return new ValidPersonBuilder(person); } // Other methods, but NO build() methods } public class InvalidPersonBuilder { private Person person; public InvalidPersonBuilder(Person person) { this.person = person; } public InvalidPersonBuilder withFirstName(String firstName) { person.setFirstName(firstName); return this; } public ValidPersonBuilder withLastName(String lastName) { person.setLastName(lastName); return new ValidPersonBuilder(person); } // Other methods, but NO build() methods } public class ValidPersonBuilder { private Person person; public ValidPersonBuilder(Person person) { this.person = person; } public ValidPersonBuilder withFirstName(String firstName) { person.setFirstName(firstName); return this; } // Other methods // Look, ma! I can build public Person build() { return person; } }
This is a huge improvement, as now developers can know at compile-time their built object is invalid.
The next step is to imagine more complex use-case:
- Builder methods have to be called in a certain order. For example, a house should have foundations, a frame and a roof. Building the frame requires having built foundations, as building the roof requires the frame.
- Even more complex, some steps are dependent on previous steps (e.g. having a flat roof is only possible with a concrete frame)
The exercise is left to interested readers. Links to proposed implementations welcome in comments.
There’s one flaw with our design: just calling the
setLastName()
method is enough to qualify our builder as valid, so passingnull
defeats our design purpose. Checking fornull
value at runtime wouldn’t be enough for our compile-time strategy. The Scala language features may leverage an enhancement to this design called the type-safe builder pattern.
Summary
- In real-life software, the builder pattern is not so easy to implement as quick examples found here and there
- Less is more: create an easy-to-use DSL is (very) hard
- Scala makes it easier for complex builder implementation’s designers than Java
Published at DZone with permission of Nicolas Fränkel, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments