Builder design pattern is traditionally linked with an object oriented programming. In a book “Design Patterns: Elements of Reusable Object-Oriented Software” builder pattern is described by GoF as:

„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.

For Elixir, as a functional programming language, we can define builder pattern as:

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

Some time ago I wrote an article how to apply that pattern to an object oriented language (“Builder design pattern in Ruby”). Now I would like to show you how we can use that construction in Elixir.

Let’s define some simple structure that reflects User :

We can build our data like this:

With that approach we have following problems:

adding new fields to the structure will only make the situation worse,

logic how the data is build is hidden in its “instantiation”.

To fix that, we can build another module that will have a knowledge on how to build a user. Such a module should allow us to create a user using different plans. It can look like this:

We can use UserBuilder to create a user like this: