lundi 3 juillet 2023

Why do we need a 'Builder class' in Builder design pattern?

In Builder design pattern a 'Builder' inner class is used through which we set the values for the fields of that class. What is the purpose of defining this class?

One of the main reasons cited for using a builder pattern is that it solves the Telescoping Constructor Problem

If so, why can't we just go ahead with setter methods?

(Note: Although there are some questions that had already discussed this topic (link) those questions and answers were not very straight forward. Hence, I had to draft this question)

For e.g., Why do this?

public class Employee {
  private int id;
  private String name;

  public Employee (Builder builder) {
    this.id = builder.id;
    this.name = builder.name;
  }

  public static class Builder {
    private int id;
    private String name;

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

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

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

// Employee emp = new Employee.Builder().id(1).name("Abc").build();

instead of this?

public class Employee {
  private int id;
  private String name;

  public Employee id(int id) {
    this.id = id;
    return this;
  }

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

// Employee emp = new Employee().id(1).name("Abc");

Aucun commentaire:

Enregistrer un commentaire