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! —

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

Krzysztof Kempiński

Written by

IT expert. Ruby on Rails/iOS/Elixir programmer. Blogger. Podcaster.

kkempin’s dev blog

Dev and life blog. Thoughts about programming, design patterns, Ruby and life.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade