Builder Pattern—Design Pattern in Plain English for Developers
Lets say you have an user interface to fetch the data for showing an advertisement campaign dashboard, that looks something like this
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:
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:
- 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!
How does this work?
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
- 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:
java-samples-for-tutorials/src/main/java/org/java/sample/tutorials/designpatterns/builder at master…
Java tutorials. Contribute to tan31989/java-samples-for-tutorials development by creating an account on GitHub.
Thanks for reading!