The mighty Builder Pattern in Object-Oriented Programming
Create objects like a PROgrammer
One of the most commonly used design patterns in the Object-Oriented world is the Builder pattern. Let’s first try to understand the motivation behind using the Builder pattern by an example. Let us consider we have a Person class with the following fields.
In order to construct an object of the Person class we have would have to pass 5 arguments to the constructor of the class as follows.
As we can see from the code above to construct a Person object we have to pass 5 arguments that need to be passed in the same order as defined in the constructor, for the things to work correctly. At least once in life we all might have misplaced the arguments in the wrong order and tried to debug the program for several hours to see why the code wasn’t working, just to figure out that the constructor arguments were swapped.
If you ever wondered if there was a better way to construct objects then you have come to the right place. Meet the powerful “Builder pattern”. Builder pattern provides a fluent API that uses chaining to create the entire object. You might have encountered the builder pattern while working with Java/Spring. Builder pattern can be seen in places where the object has a lot of fields or when the creation of an object needs to be fluent. Just in case if you are wondering how the builder pattern looks in action.
As we can see, the object creation for person class becomes a lot cleaner and simpler to understand. In order to have the builder class, we first create the PersonBuilder class which would be a fluent API (i.e., a method returns the class itself).
Note: The PersonBuilder class has been created as a static Inner class inside Person class as it makes sense for the Builder class to be inside the class its supposed to build.
The PersonBuilder class has its own Person object to which we add the data in a series of steps using separate methods for each field of Person. For example, the firstName() method is responsible for setting the firstName field, salary() method is responsible for setting the salary field, and so on. In order to convert from PersonBuilder to Person, we create a build() method which returns back the person created.
Now the only missing piece left is how to reach the PersonBuilder from Person class. We can simply add a method builder() in the Person class, that returns us the PersonBuilder from which we can continue building the object.
Note: All the source code for this article can be found in here.
That’s how we are able to create builder for any class that we wish to create. Builder pattern has a lot of variations and one such popular form is the Faceted Builder pattern. If you learned something valuable please make sure to clap the article and check out my other articles for other interesting content. That being said I thank you so much for reading it this far and see you in the next article. :)