Builder Design Pattern
Hello, in this article, I will explain the Builder Design Pattern in depth, but I will do so in very easy terms.
Let’s say you have one class User with fields firstname, lastname, age, and city where they live. If you try to make parameterized constructor for this, there would be a total of (2^n) constructors theoretically that you need to write, because for each parameter, we can include it or exclude it, so there are two choices, and then at last there is a default constructor with no parameter, so a total of 2 choices for n elements, thus total 2^n.
public class User {
private String firstName;
private String lastName;
private int age;
private String city;
// 1-field constructors
public User(String firstName) { this.firstName = firstName; }
public User(String lastName, boolean dummy) { this.lastName = lastName; }
// Dummy param to differentiate
public User(int age) { this.age = age; }
public User(String city, int dummy) { this.city = city; }
// 2-field constructors
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public User(String firstName, int age) {
this.firstName = firstName;
this.age = age;
}
public User(String firstName, String city) {
this.firstName = firstName;
this.city = city;
}
public User(String lastName, int age, boolean dummy) {
this.lastName = lastName;
this.age = age;
}
public User(String lastName, String city, boolean dummy) {
this.lastName = lastName;
this.city = city;
}
public User(int age, String city) {
this.age = age;
this.city = city;
}
// 3-field constructors
public User(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public User(String firstName, String lastName, String city) {
this.firstName = firstName;
this.lastName = lastName;
this.city = city;
}
public User(String firstName, int age, String city) {
this.firstName = firstName;
this.age = age;
this.city = city;
}
public User(String lastName, int age, String city, boolean dummy) {
this.lastName = lastName;
this.age = age;
this.city = city;
}
// 4-field constructor
public User(String firstName, String lastName, int age, String city) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.city = city;
}
}
Now, as per our example, you can see, we have made a total of 2^n - 1 = 2^4 - 1 = 15 constructors, and the last one would be the empty constructor; thus, we need to create a total of 16 constructors. Now just one more field, and the total number of constructors will blow up to 32. Now imagine what if your class has more than 10 fields? It not only looks ugly, but it is very hard to manage too. One mistake and boom, you are scratching your head in debugging for days. So, is there any better way? Yes.
When there are many fields in class and we don’t know in advance if few or all fields will be optional or not we can use the Builder Design Pattern.
As per the above definition, let’s see how the Builder Design Pattern is used in code.
public class User {
private final String firstName;
private final String lastName;
private final int age;
private final String city;
// Private constructor so objects can only be created through Builder
private User(Builder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.city = builder.city;
}
// Static inner Builder class
public static class Builder {
private String firstName;
private String lastName;
private int age;
private String city;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setCity(String city) {
this.city = city;
return this;
}
public User build() {
return new User(this);
}
}
// Getters (optional)
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public int getAge() { return age; }
public String getCity() { return city; }
}
User user1 = new User.Builder()
.setFirstName("John")
.setLastName("Doe")
.setAge(29)
.setCity("New York")
.build();
As you can see in the above example, it is much simpler and manageable. So what we did?
We made the User constructor private so it can not be invoked outside of the class.
We created an inner static class called Builder.
We defined setter methods for all fields that are the same as the User class, but instead of the return type being void, we are returning the Builder class object instance on which we set the data.
We have a build method in the Builder class that returns the User object to us.
When we want to get an instance of the User class, we will simply use User.Builder(), which will give us an instance of the Builder class, then on top of that, we will set our fields using the setters and as each setter returns the same Builder class instance for which it was invoked, we can use the setter’s chaining to set all fields that we want and skip the fields which we don’t want to set and at last we will use build() method to build the User object.
Advantages:
Readability and Clarity: No need to memorize the constructor parameter order; you just know which fields are skipped and which are set.
Flexibility in object creation: omit the optional fields that you want to
Immutability by design: as the main class does not have setter methods and fields are private, you can’t change the fields once the object is created.
Easier maintenance and evolution: no need to rewrite and refactor code when you want to add new fields, just change a few lines and write a few lines for new fields, and you are done.
Disadvantages:
More boilerplate code: you need to write the builder class.
Slight overhead for small classes: Using a builder is overkill if you have only two or three fields in class.
Not always ideal for performance-critical code: Where even micro-optimization matters, the builder class will have slight overhead, which won’t be ideal.
About the author
- I am a developer with learnings in many different languages, frameworks and technologies.
Comments
Join the discussionNo comments yet. Be the first to comment.