Builder pattern
Build objects with many optional parts one named step at a time, validate them once in build(), and get immutable results. Java and Python code, plus records and keyword arguments.
On this page
The problem: a constructor full of mystery values
A burger shop's ordering code has a Burger class with a bun, a number of patties and four optional extras. The first constructor takes all of them:
Burger b = new Burger("brioche", 2, true, false, true, false);
Which true is the cheese? Which false is the bacon? The compiler cannot help: swap two booleans and you get bacon instead of lettuce, with no error and no warning.
Mystery values and the telescoping constructor
- Some objects have lots of options. A burger has a bun, some patties, and maybe cheese, bacon, lettuce or sauce. A constructor with all of them becomes a wall of mystery values. What does the third true mean?
- Teams often add more constructors for common cases, each with one more parameter. That ladder of constructors is nicknamed the telescoping constructor, and it’s easy to pass values in the wrong order.
The usual first fix is more constructors: one with just the bun, one with the bun and patties, one with the bun, patties and cheese, and so on. This ladder is called a telescoping constructor. It grows with every option, and it still forces callers to pass false for every option that comes before the one they want.
The second usual fix is an empty constructor plus setters (b.setCheese(true)). That reads well, but now the object exists in a half-built state between calls, it can be changed by anyone later, and there is no single moment where you can check that the whole combination is valid.
The idea: name each step, check once, then create
The Builder pattern moves construction into a separate object. You call one named method per choice, skip the ones you don't need, and finish with build(), which validates the whole combination and only then creates the product. Each step returns the builder itself, so the calls chain together: that style is called method chaining (or a fluent interface).
Chain the steps, then build() checks and creates
- The Builder pattern lets you build the object one named step at a time. Each step returns the builder, so the calls chain together, and you simply skip the options you don’t want. That style is called method chaining.
- build() is the last step. It checks the rules, say “a burger needs a bun and at least one patty”, and only then creates the burger. The finished object can be immutable: it never changes after it’s built.
| Role | In this example | Responsibility |
|---|---|---|
| Product | Burger | The finished object. Usually immutable: its fields never change after construction. |
| Builder | Burger.Builder | Collects the choices in mutable fields, one method per option. |
build() | Builder.build() | Checks rules that involve several fields, then calls the product's private constructor. |
| Director (optional) | Menu.classicCheeseburger(builder) | A function that runs a fixed sequence of steps for a common recipe. Rare in modern code. |
Build it step by step
1. The product has only final fields and a private constructor that takes the builder, so the only way to get a Burger is through build().
2. Required values go into the builder's constructor (new Builder("brioche")). The compiler then enforces them; you cannot forget the bun.
3. Optional values each get a method that sets a field and return this.
4. build() validates and creates. Collections are copied, so changing the builder afterwards cannot change a burger that was already built.
import java.util.*;
final class Burger {
private final String bun; // required
private final int patties; // required, 1-4
private final boolean cheese; // optional
private final boolean bacon; // optional
private final List<String> sauces; // optional, 0 or more
private Burger(Builder b) { // only the builder can call this
this.bun = b.bun;
this.patties = b.patties;
this.cheese = b.cheese;
this.bacon = b.bacon;
this.sauces = List.copyOf(b.sauces); // immutable copy
}
public String bun() { return bun; }
public int patties() { return patties; }
public boolean hasCheese() { return cheese; }
public boolean hasBacon() { return bacon; }
public List<String> sauces() { return sauces; }
@Override public String toString() {
return bun + " bun, " + patties + " patties"
+ (cheese ? ", cheese" : "") + (bacon ? ", bacon" : "") + ", sauces=" + sauces;
}
public static final class Builder {
private final String bun;
private int patties = 1; // sensible default
private boolean cheese;
private boolean bacon;
private final List<String> sauces = new ArrayList<>();
public Builder(String bun) { this.bun = Objects.requireNonNull(bun, "bun"); }
public Builder patties(int n) { this.patties = n; return this; }
public Builder cheese() { this.cheese = true; return this; }
public Builder bacon() { this.bacon = true; return this; }
public Builder sauce(String s) { this.sauces.add(s); return this; }
public Burger build() {
if (patties < 1 || patties > 4)
throw new IllegalStateException("patties must be 1-4, got " + patties);
if (bacon && sauces.contains("vegan mayo"))
throw new IllegalStateException("bacon with vegan mayo? pick one");
return new Burger(this);
}
}
}
public class Main {
public static void main(String[] args) {
Burger b = new Burger.Builder("brioche")
.patties(2)
.cheese()
.sauce("chipotle")
.build();
System.out.println(b); // brioche bun, 2 patties, cheese, sauces=[chipotle]
try {
new Burger.Builder("sesame").patties(0).build();
} catch (IllegalStateException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}from dataclasses import dataclass
@dataclass(frozen=True) # immutable once created
class Burger:
bun: str
patties: int
cheese: bool
bacon: bool
sauces: tuple[str, ...]
class BurgerBuilder:
def __init__(self, bun: str): # required value
self._bun = bun
self._patties = 1
self._cheese = False
self._bacon = False
self._sauces: list[str] = []
def patties(self, n: int) -> "BurgerBuilder":
self._patties = n
return self # allows chaining
def cheese(self) -> "BurgerBuilder":
self._cheese = True
return self
def bacon(self) -> "BurgerBuilder":
self._bacon = True
return self
def sauce(self, name: str) -> "BurgerBuilder":
self._sauces.append(name)
return self
def build(self) -> Burger:
if not 1 <= self._patties <= 4:
raise ValueError(f"patties must be 1-4, got {self._patties}")
if self._bacon and "vegan mayo" in self._sauces:
raise ValueError("bacon with vegan mayo? pick one")
return Burger(self._bun, self._patties, self._cheese,
self._bacon, tuple(self._sauces))
burger = (BurgerBuilder("brioche")
.patties(2)
.cheese()
.sauce("chipotle")
.build())
print(burger)
try:
BurgerBuilder("sesame").patties(0).build()
except ValueError as e:
print("Rejected:", e)Why validate in build() and not in each setter?
Some rules involve one field ("patties between 1 and 4") and could be checked in the setter. Others involve several fields together ("no bacon with vegan mayo"), and the order of calls is free, so the only safe moment is when the caller says "I'm done". Checking in build() also means an invalid Burger never exists, not even briefly. Code that receives a Burger can trust it without re-checking.
Lighter alternatives you should know
A builder is a workaround for a language that lacks named and default arguments. When the language has them, you often don't need the pattern at all.
| Option | What it looks like | Validation of the whole object | Good when |
|---|---|---|---|
| Python keyword arguments + frozen dataclass | Burger(bun="brioche", patties=2, cheese=True) | __post_init__ | Almost always, in Python |
| Kotlin named and default parameters | Burger(bun = "brioche", cheese = true) | init { require(...) } | Almost always, in Kotlin |
| Java record with a compact constructor | new Burger("brioche", 2, true, false, List.of()) | Compact constructor | Few fields (up to about 4), all required |
Lombok @Builder | Generated Burger.builder().bun("brioche").build() | Only if you put @Builder on a constructor that validates | Many fields, and the team already uses Lombok |
| Hand-written builder | As above | build() | Many optional fields, cross-field rules, public APIs |
// A record: immutable, equals/hashCode/toString for free, validated in one place.
// Still positional, so it suits few fields.
record Burger(String bun, int patties, boolean cheese, boolean bacon, List<String> sauces) {
Burger { // compact constructor
Objects.requireNonNull(bun, "bun");
if (patties < 1 || patties > 4) throw new IllegalArgumentException("patties must be 1-4");
sauces = List.copyOf(sauces); // defensive, immutable copy
}
}from dataclasses import dataclass, replace
@dataclass(frozen=True, kw_only=True) # every argument must be named
class Burger:
bun: str
patties: int = 1
cheese: bool = False
bacon: bool = False
sauces: tuple[str, ...] = ()
def __post_init__(self): # validates the whole object
if not 1 <= self.patties <= 4:
raise ValueError(f"patties must be 1-4, got {self.patties}")
b = Burger(bun="brioche", patties=2, cheese=True, sauces=("chipotle",))
with_bacon = replace(b, bacon=True) # a modified copy, also validatedIn Python, a hand-written builder mostly earns its place when construction is genuinely incremental: options arrive from several places over time (a query builder that adds WHERE clauses as filters are parsed), or when the builder does real work in build(), like SQLAlchemy's select(...).where(...).
Builder compared with its look-alikes
| Builder | Factory Method | Abstract Factory | Plain constructor | |
|---|---|---|---|---|
| Question it answers | How is one complex object assembled? | Which class should be created? | Which family of related objects? | Nothing to decide |
| Steps | Many calls, then build() | One call | One call per product | One call |
| Typical size | 5+ fields, many optional | Any | Any | 1 to 4 fields |
| Result | Usually one immutable object | An object of some subclass | Matching objects (e.g. dark-theme button and menu) | The object |
They combine well: a factory can decide which product to make and use a builder to assemble it.
Step builders: making the compiler enforce order
A step builder (or staged builder) returns a different interface after each required step, so build() only becomes available once every required value has been given:
interface NeedsBun { NeedsPatties bun(String bun); }
interface NeedsPatties { Optionals patties(int n); }
interface Optionals { Optionals cheese(); Optionals sauce(String s); Burger build(); }
// Burger.start().bun("brioche").patties(2).cheese().build(); compiles
// Burger.start().patties(2) ... does not compile
One class can implement all three interfaces. It costs an interface per required step, so keep it for public APIs where misuse is common. Libraries such as jOOQ use the same idea so that many invalid SQL statements fail to compile.
When not to use it
Real uses
- Java:
HttpRequest.newBuilder(),Stream.builder(),Locale.Builder, Protocol Buffers message builders (Person.newBuilder().setName("Ana").build()), OkHttp'sRequest.Builder, Android'sAlertDialog.Builder. StringBuilderis often named as an example. It is a mutable accumulator rather than the textbook pattern, but it shares the idea: collect pieces cheaply, then produce an immutableStringwithtoString().- Tests: test data builders (
aUser().withRole(ADMIN).build()) give every field a valid default, so each test only states what matters to it.
In the interview
Your app sends notifications. Each has a recipient and a channel (email, SMS or push), and optionally a subject, a body, a priority (default normal) and up to 5 attachments. Rules: email needs a subject; SMS bodies are at most 160 characters; SMS cannot have attachments. Sketch the builder: which values go in its constructor, and what does build() check?
Compare with our answer
Notification n = new Notification.Builder("ana@example.com", Channel.EMAIL)
.subject("Your order shipped")
.body("It arrives Friday.")
.attach(invoicePdf)
.build();
// inside Builder
public Notification build() {
if (channel == Channel.EMAIL && subject == null) throw new IllegalStateException("email needs a subject");
if (channel == Channel.SMS && body.length() > 160) throw new IllegalStateException("SMS body over 160 chars");
if (channel == Channel.SMS && !attachments.isEmpty()) throw new IllegalStateException("SMS has no attachments");
if (attachments.size() > 5) throw new IllegalStateException("at most 5 attachments");
return new Notification(this); // copies attachments with List.copyOf
}
n = (NotificationBuilder("ana@example.com", Channel.EMAIL)
.subject("Your order shipped")
.body("It arrives Friday.")
.attach(invoice_pdf)
.build())
# inside NotificationBuilder
def build(self) -> Notification:
if self._channel is Channel.EMAIL and self._subject is None:
raise ValueError("email needs a subject")
if self._channel is Channel.SMS and len(self._body) > 160:
raise ValueError("SMS body over 160 chars")
if self._channel is Channel.SMS and self._attachments:
raise ValueError("SMS has no attachments")
if len(self._attachments) > 5:
raise ValueError("at most 5 attachments")
return Notification(self._to, self._channel, self._subject, self._body,
self._priority, tuple(self._attachments))
A strong answer mentions: recipient and channel in the builder's constructor because they are required · defaults for priority and body · cross-field rules (channel with subject, length and attachments) checked together in build() · an immutable product with a copied attachment list · a clear exception message for each rule.
Product now says a notification may have either a recipient address or a user id that is looked up later, but never both and never neither. Six call sites already use new Builder(recipient, channel). How do you change the design without breaking them, and how do you stop someone building one with neither?
Compare with our answer
A strong answer mentions: keep the existing constructor working (or add static entry points such as Builder.toAddress(...) and Builder.toUser(...)) · an "exactly one of address or user id" rule in build() · a step builder or two entry points so the compiler rules out "neither" · tests for both, neither and each alone · deprecating the old constructor only once callers have moved.
- Intent: construct a complex object step by step with named methods, then create it in one validated
build()call. - Fixes: mystery positional arguments, telescoping constructors, half-built objects from setters.
- Shape: private product constructor taking the builder · required values in the builder's constructor ·
return thisfor chaining ·build()validates cross-field rules. - Product: immutable (
finalfields, copied collections), so it is safe to share and cache. - Builder: mutable and single-use; not thread-safe.
- Alternatives: Python keyword arguments +
@dataclass(frozen=True)with__post_init__; Kotlin named defaults; Java records for few fields; Lombok@Builderon a validating constructor. - Not a factory: a factory picks which class; a builder assembles one object.
- Skip it for a handful of required fields or when named arguments exist.
1. A Report class has 11 constructor parameters, 8 of them optional booleans and numbers, and bugs keep appearing from arguments passed in the wrong order. Which change fixes the root cause best in Java?
Named builder methods remove the ordering problem and give one place to check the whole object. More constructors is the telescoping problem again; setters create half-built, mutable objects with no single validation point.
2. Why do builders usually validate in build() rather than in each setter method?
Callers may set fields in any order, so a rule like "email needs a subject" can only be checked once everything is in. Setters can throw, and they can still return this.
3. A builder method sauces(List<String> s) stores the caller's list directly, and the product keeps the same reference. What can go wrong?
final only stops the field being reassigned, not the list being changed. Copy with List.copyOf (or a tuple in Python) so the built object is really immutable.
4. A Python team asks whether to add a builder for a class with 9 optional settings. What is the most idiomatic answer?
Keyword arguments already name every value and allow skipping options; __post_init__ can check cross-field rules. Builders still help when construction is spread out over time, as in query builders.
5. What distinguishes Builder from Factory Method?
Factory Method answers "which class?" in a single call. Builder answers "how is this one object put together?" across several calls, ending in build().
6. You add a required warehouseId field to an order and expose it as a normal builder method. Months later an order fails in production with "warehouseId missing". What design change prevents this class of bug at compile time?
A setter-style method can be forgotten and only build() notices, at run time. Required values in the constructor (or a staged interface) make omission a compile error. A default of zero hides the bug.
7. Two threads share one Burger.Builder instance and each calls a few setters and then build(). What is the likely outcome?
Builders are mutable and not thread-safe; interleaved setters mix values. Use one builder per construction. The built, immutable product is the part that is safe to share.
Score 60% or more and the lesson is marked complete.