Builder design pattern in Elixir

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:

So we are using simple functions to build selected part of a user. We can pick different functions to achieve multiple plans. And finally, we can have an algorithm (or logic) how some parts of a user are created, closed in the builder module (login_credentials).


Want to know first about new articles from that blog?

Subscribe to my newsletter now! — http://eepurl.com/cVPm_v


If you like this article and consider it useful for you, please support it with 👏.