Sobes.tech
Junior — Middle

What reasons make the Builder pattern justified?

sobes.tech AI

Answer from AI

The Builder pattern is justified in the following cases:

  • When the object is complex and has many parameters, especially if some of them are optional.
  • If there is a need to create different variations of an object with a similar structure.
  • To avoid constructors with a long list of parameters (like a phone code), which improves code readability and maintainability.
  • For step-by-step object construction, where the order of setting parameters is important or parameters depend on each other.

Example in Java:

public class Computer {
    private String CPU;
    private int RAM;
    private int storage;

    private Computer(Builder builder) {
        this.CPU = builder.CPU;
        this.RAM = builder.RAM;
        this.storage = builder.storage;
    }

    public static class Builder {
        private String CPU;
        private int RAM;
        private int storage;

        public Builder setCPU(String CPU) {
            this.CPU = CPU;
            return this;
        }

        public Builder setRAM(int RAM) {
            this.RAM = RAM;
            return this;
        }

        public Builder setStorage(int storage) {
            this.storage = storage;
            return this;
        }

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

// Usage:
Computer pc = new Computer.Builder()
    .setCPU("Intel i7")
    .setRAM(16)
    .setStorage(512)
    .build();

This approach improves readability and flexibility in object creation.

What reasons make the Builder pattern justified? — Java - sobes.tech