Patterns for creating objects · Chapter 9

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.

BeginnerInterview priority: Medium40 min
On this page
  1. The problem: a constructor full of mystery values
  2. The idea: name each step, check once, then create
  3. Build it step by step
  4. Lighter alternatives you should know
  5. Builder compared with its look-alikes
  6. When not to use it
  7. Real uses
  8. In the interview
  9. Quiz

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

  1. 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?
  2. 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

  1. 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.
  2. 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.
RoleIn this exampleResponsibility
ProductBurgerThe finished object. Usually immutable: its fields never change after construction.
BuilderBurger.BuilderCollects 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());
        }
    }
}

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.

OptionWhat it looks likeValidation of the whole objectGood when
Python keyword arguments + frozen dataclassBurger(bun="brioche", patties=2, cheese=True)__post_init__Almost always, in Python
Kotlin named and default parametersBurger(bun = "brioche", cheese = true)init { require(...) }Almost always, in Kotlin
Java record with a compact constructornew Burger("brioche", 2, true, false, List.of())Compact constructorFew fields (up to about 4), all required
Lombok @BuilderGenerated Burger.builder().bun("brioche").build()Only if you put @Builder on a constructor that validatesMany fields, and the team already uses Lombok
Hand-written builderAs abovebuild()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
    }
}

In 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

BuilderFactory MethodAbstract FactoryPlain constructor
Question it answersHow is one complex object assembled?Which class should be created?Which family of related objects?Nothing to decide
StepsMany calls, then build()One callOne call per productOne call
Typical size5+ fields, many optionalAnyAny1 to 4 fields
ResultUsually one immutable objectAn object of some subclassMatching 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's Request.Builder, Android's AlertDialog.Builder.
  • StringBuilder is 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 immutable String with toString().
  • 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 turn: a notification builder

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.

Your turn: the requirement changes

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.

Builder on one page
  • 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 this for chaining · build() validates cross-field rules.
  • Product: immutable (final fields, 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 @Builder on 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.
Interactive labPractise it: take burger orders without mixing up the extrasOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

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?

2. Why do builders usually validate in build() rather than in each setter method?

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?

4. A Python team asks whether to add a builder for a class with 9 optional settings. What is the most idiomatic answer?

5. What distinguishes Builder from Factory Method?

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?

7. Two threads share one Burger.Builder instance and each calls a few setters and then build(). What is the likely outcome?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.