According to GoF and their great book “Design Patterns: Elements of Reusable Object-Oriented Software”, builder pattern:

„Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

and it’s a part of an object creational design patterns.

Builder pattern is useful when the algorithm how to build an object is something independent of the parts that makes the object (methods that are building the object). That also defines another applicability of builder pattern: it’s helpful when there can be many ways of building complex objects.

Let’s start with some example and see how we can improve/refactor it by using builder patter.

Let’s assume we have that way of creating users:

There are few problems with that approach:

it doesn’t look professional ;)

we have very long list of params which limits us with the ways we can instantiate a new user. To do this, you can sent nil for certain params but it can look very messy soon,

for certain params but it can look very messy soon, adding new params will only make the situation worse,

logic how the object is build is hidden in its instantiation.

To extract the logic how the user is build we can use builder pattern here.

Our User class should be simple:

and we want to instantiate new user by doing this:

We are telling our builder ( UserBuilder ) how to build new user by giving him exact plan (represented by the block in that example).

Two benefits that are obvious here: no long list of parameters and algorithm how the user is build is outside User class.

Let’s implement UserBuilder class.

UserBuilder has the knowledge how to build parts of the User . It gives us some more digestible way of building new object( set_name , set_as_active , …) than just instantiation of User from the first example (we don’t have to know about some low level detail of what parts build a user object).