Design Patterns, Builder

The Builder is a design pattern which belongs to the family of creational design patterns. It comes very handy when an object is complicated to create (i.e has too many fields) or when the developer needs to control the initialization of an object.

Using the Builder pattern, the construction of a complicated object is encapsulated and controlled only at one place. That way, the user can modify the creation logic, or even the object, without having to find every place where the object’s constructor is called.

Additionally, another use case of the Builder pattern is when some validation on an object’s field’s value needs to happen prior initialization (e.g email validation).

Take for example the below constructor:

Even though at the moment the constructor does not seem too complicated, imagine in the future the developer needs to add one or more fields. He/She will need to change every line of code that initializes a Person object.

Moreover, what if the developer needs to validate the fields prior to object’s construction. Those things can be solved using a builder. I like having the builder as a separate static inner class of the object that it builds.

An example of a PersonBuilder, which performs some validation prior to object creation, is the below:

The full example along with some unit tests can be found on Github.