Construction needs more Builders

A brief introduction to the Builder Programming Pattern.

Until recently, my favourite way to create a pizza was akin to the following.

This is a perfectly legal way to create your pizza, but I wouldn’t be impressed when my 16” pizza arrived with:

I thought I ordered a 16” Hawaiian — Cheese, ham and pineapple with no sausage?

The problem with creating a pizza this way, is that, we don’t know the meaning for each of those True/False options. We could investigate the code or documentation, however doing so would waste valuable pizza eating time. This is especially true if you must investigate multiple occurrences. By extension, everyone reading your code will also waste their time.

Pizza Problems

What if I wanted a cheese only pizza — Margherita?

new Pizza(Diameter, Anchovies, Spinach, Broccoli, Cheese);

Now knowing the order of options, I would use the following code.

After appropriate chagrin, I specify

The main points so far:

  • People shouldn’t have to opt in/out to each topping on the menu.
  • I shouldn’t need to specify no to each topping I don’t want, to get to a topping I do want.
  • It is difficult at first glance without the colours, to see which option means which topping.

These issues can be solved using a Builder Pattern.

How to avoid an Anchovy, Spinach and Broccoli pizza

The Builder Pattern describes a way of constructing objects without the problems mentioned above.

My Margherita pizza can now be simplified as:

My Hawaiian can be simplified as:

And if I wanted to create both at once, I can specify “addCheese” and re-use the builder.

The Fluent Interface programming style specifies that each method (e.g. “.addCheese()”) should return the object it is called on. This allows us to write code that is more natural to read and has a different feel to the code we had in the beginning.

  • We can now specifically specify the toppings we want
  • It is now much easier to see what each pizza is made from
  • The only mandatory field is now the pizza Diameter
  • We can re-use the builder to create multiple pizzas

If you’re interested in the specifics of Fluent Interfaces, I can highly recommend this guide:

https://www.martinfowler.com/bliki/FluentInterface.html

A nice guide on the Builder Pattern can be found below:

https://jlordiales.wordpress.com/2012/12/13/the-builder-pattern-in-practice/

share this post

 let's have a proper conversation contact us
A circle used for styling a banner

more to explore

A circle used for styling a banner

2021 has been an eventful year!

We’re looking back and reflecting on everything we’ve achieved this year. Thank you to everyone who has worked with us this year. We’ve been fortunate

we create and deliver captivating content that audiences engage with.

we build and evolve robust platforms that people want to use.

we design and manage effective campaigns that exceed set targets

A circle used for styling a banner