Java › Design Patterns in Java
How does the Builder pattern solve the "telescoping constructor" problem, and how would you implement it for a class with many optional parameters?
IntermediateAnswer
The telescoping constructor problem arises when a class has many optional fields, leading to an unwieldy proliferation of overloaded constructors covering various combinations of provided parameters -- the Builder pattern instead uses a separate, often static nested Builder class with fluent setter-like methods (each returning `this` for chaining) that accumulate configuration before a final build() method constructs the actual immutable target object, giving readable, self-documenting object construction regardless of how many optional fields exist, without needing dozens of constructor overloads.
public class Pizza {
private final String size;
private final boolean cheese, pepperoni, mushroom;
private Pizza(Builder b) {
size = b.size; cheese = b.cheese; pepperoni = b.pepperoni; mushroom = b.mushroom;
}
public static class Builder {
private final String size;
private boolean cheese, pepperoni, mushroom;
public Builder(String size) { this.size = size; }
public Builder cheese(boolean val) { cheese = val; return this; }
public Builder pepperoni(boolean val) { pepperoni = val; return this; }
public Pizza build() { return new Pizza(this); }
}
}
Pizza pizza = new Pizza.Builder("large").cheese(true).pepperoni(true).build();Real-world example An HTTP client configuration class with a dozen optional settings (timeout, retry policy, headers, proxy, etc.) uses a Builder, letting callers set only the specific options relevant to them via readable chained method calls, avoiding both an unwieldy multi-parameter constructor and error-prone positional argument ordering.