Rules to build “Builder Pattern”

What is a builder pattern?
Create a complex object by separating the creation process from the representation. Builder pattern gives you the freedom to set property values in a chained manner, not required to set values for optional properties that are set automatically with their default values. Using method chaining (chained manner), we achieve readability and maintainability of object creation.

In, Part 1, we discuss the complete requirements of the builder design pattern. Please go through it.

Rules to build “Builder Pattern”: To achieve flexibility, immutability, and readability in object creation.

  • Private Constructor.
  • Static Inner Class.
  • Return the Builder.
  • Build Method.

1. Private Constructor: In the builder pattern, the private constructor ensures that the object is created through a dedicated builder class only, not from outside the class. Because of the private constructor and final properties, objects are created immutable and the object’s state cannot be changed after creation.

private Student(StuldentBuilder builder) {  // Private constructor
    this.name = builder.name;
    this.rollNo = builder.rollNo;
}

2. Static Inner Class: Static inner class helps to encapsulate (OOPS principle) the object-building logic. It is a dedicated builder class to build complex objects by having access to the private constructor. By avoiding setters, objects state also cannot be changed.

public class Student {
    private final String name;
    private final int rollNo;

    private Student(StudentBuilder builder) {
        this.name = builder.name;
        this.rollNo = builder.rollNo;
    }

    public static class StudentBuilder {
        private String name;
        private int rollNo;

        public StudentBuilder setName(String name) {
            this.name = name;
            return this;
        }

        public StudentBuilder setAge(int rollNo) {
            this.rollNo = rollNo;
            return this;
        }

        public Student build() {
            return new Student(this);
        }
    }
}

3. Return Builder: All the methods in the static inner class (builder class) must return the builder itself. The “returning builder itself” from every method of the builder class enables the method-chaining. Method chaining is a very common coding practice. For example, method chaining is used in lambda expression. As per the above Builder Pattern example, “setName” and “setAge” return the builder.

4. Build Method: The most important build() method returns the builder object (immutable object) and is mandatory to call in the last as a terminal method.

public Student build() {
    if (this.name == null) {
        throw new IllegalStateException("Name is required");
    }
    return new Student(this);
}

Leave a Reply

Your email address will not be published. Required fields are marked *