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.
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:
A nice guide on the Builder Pattern can be found below: