Junior
What are the advantages of the Builder design pattern compared to a regular constructor?
sobes.tech AI
Answer from AI
- Code Readability: Allows creating objects with a large number of optional parameters, making the initialization process more explicit and understandable.
- Flexibility: Simplifies management of optional parameters and their combinations.
- Safety: Ensures that the object is only created after all necessary parameters are set, preventing the creation of invalid states.
- Avoidance of telescoping constructors: Solves the problem of increasing number of constructors as the number of parameters grows.
Example:
// Class with Builder
public class User {
private final String firstName;
private final String lastName;
private final int age; // Optional
private User(Builder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
}
public static class Builder {
private final String firstName;
private final String lastName;
private int age;
public Builder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Builder age(int age) {
this.age = age;
return this;
}
public User build() {
// Check required parameters
if (firstName == null || lastName == null) {
throw new IllegalStateException("First and last name are required.");
}
return new User(this);
}
}
// Getters...
}
// Using Builder
User user = new User.Builder("Ivan", "Petrov")
.age(30)
.build();
// Comparison with a regular constructor (without Builder)
// The variant with many optional parameters requires multiple constructors or passing null