Builder Pattern—Design Pattern in Plain English for Developers

Nagaraj Tantri
3 min readJan 16, 2022

Lets say you have an user interface to fetch the data for showing an advertisement campaign dashboard, that looks something like this

Simple UI to capture the details for a advertising data

If you observe closely this dashboard has a set of inputs/controls:

  • Mandatory parameters — like Advertiser, Campaign, Start Date & End Date
  • Optional parameters — like Exclude In-Active Users, Limit Data, Budget, Compare with Competitors.
  • Button to fetch & Graphs to display — An action and a result

Now, think how can we represent this data operation in our code (assume like using Java to store data).

Immediately, the usual thing that comes to our mind is to represent all the above parameters as a class object and then perform the action. A typical class that looks like:

Typical Class to Hold the Data from UI

You see the pattern, multiple constructors to ensure that we can handle optional parameters. Also, ensuring to have so many setters to provide access to set the data.

What is the drawback/problems of the above usage?

  • Too many Constructors: Different types of constructors to support optional parameters. For example:
Constructors are going to be painful to handle and remember the options
  • Object Setters (too many modifications): Maintaining the setters to allow/not allow parameters becomes very tedious. What if you want to make it immutable? Then again option one, i.e, constructor
  • Open/Close principle violation: The more optional parameters comes along, we need to adjust the object creation logic.

Is there a better way?

Yes, there is an awesome way and that is the Builder Pattern!

Builder Pattern

How does this work?

Choose the main constructor and build the object more effectively

So, as you see above, here’s the main highlight:

  • Immutable state: Once the object data is set, you can’t modify the data
  • Optional requirements of an object can be handled via better functional representations and easier to read
  • Open/Close principle of S.O.L.I.D principles is easy now, all you can do is modify and still is effective to extend the class with more functionality for optional parameters.
  • Default values to be added: It’s also easy to add default values like dontShowInActiveData
  • Neater call representation to ensure we don’t need object reference always

A builder pattern is very useful if we want to create different representations of a complex object or encapsulate creating and assembling the parts of a complex object in a separate Builder object. Hope this was useful! You can checkout this example in more detail in my GitHub repository:

Thanks for reading!

--

--

Nagaraj Tantri

Coded! Loves to solve problems. An engineer by heart.