Photo by James Kovin on Unsplash

Build complex objects step by step

Swift — Problems Catalogue #2

Alex Ilovan
Published in
3 min readJun 7, 2022

--

Problem Definition:

Consider the following scenario:

You have to implement a build your own Sandwich App 🥪 but with a twist. The app needs to guide the user through a story of wonder and delight—every step of the way every ingredient is masterfully displayed to the user with scrumptious animations and effects.

Basically, you have a multi-screen carousel in which you need to build the object step by step. You can already sense where this is going. We need a solution for creating an object in the first phase and filling it with data in different phases.

Problem Solution:

Builder — it’s a creational design pattern that lets you build objects step by step.

Real-World Usage:

Let’s create a Sandwich Maker App:

First, as usual, let’s start with a protocol. A Builder Protocol. You never know when you want to white label the App and create a Cupcake Maker App 🧁

For simplicity's sake, let’s just add a method for adding the first and second ingredients and of course a topping adder.

Builder Protocol

Next, let’s create the Sandwich model class. Here let’s just have an array of ingredients, a method for adding ingredients to that array and of course a method for listing the ingredients.

Sandwich class

Now, the builder. Again, for simplicity’s sake, let’s create a sandwich variable and methods for adding the first ingredient, the second ingredient and of course the topping with the amazing “Garlic Sauce” ✨

Let’s also add a reset method for refreshing the sandwich variable and of course a method for returning our Sandwich 😍

Sandwich Builder

Last but not least, the SandwichApp class in which we put everything together.

By using a builder, we can create a sandwich in different phases quite easily. This is a very simple example but the builder pattern can be refined and used for really complex objects.

SandwichApp Class

From this point on, the sky is the limit 🚀 well…almost.

Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.

This is the second article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.

Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶

--

--

Alex Ilovan
salt&pepper

🚀Head of Mobile Development @S&P 💻Comp. Engineer 🪐Engineering Manager. You can visit at: https://www.linkedin.com/in/alex-ilovan-129161b4/