Lesson 26 / 38
Builder Pattern
Construct complex immutable objects step by step with a fluent Builder, avoiding constructors with long parameter lists and telescoping overloads.
The telescoping constructor problem
When a class has many optional fields, a constructor with 6+ parameters (or a family of overloads for every combination) becomes unreadable and error-prone — it's easy to swap two int arguments by accident. A Builder fixes this with named, chainable setters.
A fluent Builder
Each with*/setter returns this, so calls chain; build() produces the final immutable object. Records with many optional fields, and libraries like Lombok's @Builder, generate this boilerplate for you.
class Pizza {
private final String size;
private final List<String> toppings;
private Pizza(Builder b) { this.size = b.size; this.toppings = b.toppings; }
static class Builder {
private String size = "medium";
private List<String> toppings = new ArrayList<>();
Builder size(String s) { this.size = s; return this; }
Builder addTopping(String t) { toppings.add(t); return this; }
Pizza build() { return new Pizza(this); }
}
}
Pizza p = new Pizza.Builder().size("large").addTopping("olives").build();