Builder
Builder is the creational pattern you're most likely to use every week, often without writing one. HttpRequest.newBuilder(), StringBuilder, ProcessBuilder, a query builder in your ORM and the generated builders on every protobuf message are all versions of it. It solves an everyday problem: an object needs many inputs, some required and some optional, and you want construction to be readable, validated and finished in one go.
There are really two patterns under the one name. The original GoF Builder separates a construction process (run by a "director") from the representation being built, so the same steps can produce different outputs. The version popularised by Joshua Bloch's Effective Java is about something more modest: replacing long constructors with a fluent, validated builder that produces an immutable object. This page covers both, then shows step builders, which turn missing required fields into compile errors, and finally the idiomatic alternatives in Python and TypeScript that make most hand-written builders unnecessary. The creational patterns page has a query-builder example. This page goes further.
| Category | Creational |
| Solves | Many constructor parameters, optional fields, multi-step construction, invalid half-built objects |
| Main cost | Every field is declared twice (product and builder), and a builder without validation adds nothing |
| Modern form | Named or keyword arguments, options objects, records with compact constructors, generated builders |
Intent
Separate the construction of a complex object from the object itself, so that construction can happen step by step, be validated as a whole, and finish by producing a complete (usually immutable) product. In the GoF form, the same construction steps can also produce different representations.
The problem
A flight-search service accepts searches with three required fields (origin, destination and departure date) and several optional ones: a return date, passengers (default 1), cabin class (default economy), a maximum number of stops, and whether dates are flexible. There are also rules: the return date can't be before departure, and passengers must be between 1 and 9.
The first attempt uses telescoping constructors: one constructor per combination of optional fields, each calling the next.
import java.time.LocalDate;
class TripSearch {
final String from, to;
final LocalDate depart, returnDate;
final int passengers, maxStops;
final String cabin;
final boolean flexible;
TripSearch(String from, String to, LocalDate depart) {
this(from, to, depart, null);
}
TripSearch(String from, String to, LocalDate depart, LocalDate returnDate) {
this(from, to, depart, returnDate, 1);
}
TripSearch(String from, String to, LocalDate depart, LocalDate returnDate, int passengers) {
this(from, to, depart, returnDate, passengers, "ECONOMY", 2, false);
}
TripSearch(String from, String to, LocalDate depart, LocalDate returnDate,
int passengers, String cabin, int maxStops, boolean flexible) {
this.from = from; this.to = to; this.depart = depart; this.returnDate = returnDate;
this.passengers = passengers; this.cabin = cabin; this.maxStops = maxStops; this.flexible = flexible;
}
}
public class Before {
public static void main(String[] args) {
LocalDate out = LocalDate.of(2026, 12, 20), back = LocalDate.of(2026, 12, 27);
// Which int is passengers and which is maxStops? What does `true` mean?
TripSearch a = new TripSearch("DEL", "BOM", out, back, 0, "BUSINESS", 2, true);
// Swapped dates and swapped airports compile fine: same types.
TripSearch b = new TripSearch("BOM", "DEL", back, out);
if (a.passengers != 0) throw new AssertionError("an invalid search was accepted");
if (!b.returnDate.isBefore(b.depart)) throw new AssertionError("return before departure was accepted");
System.out.println("constructed two invalid searches without a single error");
}
}
from datetime import date
class TripSearch:
def __init__(self, origin, destination, depart, return_date=None,
passengers=1, cabin="ECONOMY", max_stops=2, flexible=False):
self.origin, self.destination = origin, destination
self.depart, self.return_date = depart, return_date
self.passengers, self.cabin = passengers, cabin
self.max_stops, self.flexible = max_stops, flexible
out, back = date(2026, 12, 20), date(2026, 12, 27)
# Positional call: is 2 the passenger count or the stop limit? Nothing checks.
s = TripSearch("DEL", "BOM", back, out, 0, "BUSINESS", 2, True)
assert s.passengers == 0 and s.return_date < s.depart
s.passengers = 3 # and anyone can change it afterwards
print("invalid search accepted, then mutated")
What goes wrong:
- Call sites are unreadable.
new TripSearch("DEL", "BOM", out, back, 0, "BUSINESS", 2, true)gives no hint whichintis which, or whattruemeans. - Same-typed parameters swap silently. Two
Strings, twoLocalDates and twoints in a row mean the compiler can't catch transposed arguments. - The combinations explode. With five optional fields, a constructor for every useful subset is impossible, so callers pass placeholder values (
null,0,false) for fields they don't care about. - Validation has nowhere good to live. You could validate in the biggest constructor, but rules that involve several fields (return after departure) get tangled with defaults.
The common alternative, the JavaBeans style (a no-argument constructor plus setters), fixes readability but introduces worse problems: the object exists in an invalid, half-configured state between setter calls, it can't be immutable, and it can't be safely shared between threads while it's being set up.
Builder keeps the readability of setters and the safety of a constructor: you set fields by name on a separate builder object, then call build(), which validates everything at once and returns a finished, immutable product.
Structure
The everyday (Bloch-style) builder is a nested class that mirrors the product's fields:
classDiagram
class TripSearch {
-from String
-to String
-depart LocalDate
-returnDate LocalDate
-passengers int
-TripSearch(builder)
+builder(from, to, depart)$ Builder
+toBuilder() Builder
}
class Builder {
-from String
-to String
-depart LocalDate
-returnDate LocalDate
-passengers int
+returnOn(date) Builder
+passengers(n) Builder
+cabin(c) Builder
+build() TripSearch
}
class Client
Client ..> Builder : configures
Builder ..> TripSearch : builds
TripSearch *-- Builder : nested class
The GoF builder adds a director that knows the sequence of steps, and lets several concrete builders produce different representations from the same steps:
classDiagram
class Director {
+construct(builder)
}
class ItineraryBuilder {
<<interface>>
+addFlight(flight)
+addHotel(hotel)
}
class TextItineraryBuilder {
+result() String
}
class CalendarItineraryBuilder {
+result() List
}
Director --> ItineraryBuilder : drives
ItineraryBuilder <|.. TextItineraryBuilder
ItineraryBuilder <|.. CalendarItineraryBuilder
Participants
- Product (
TripSearch). The complex object being built. In the Bloch style it has a private constructor that takes the builder, and it's usually immutable. - Builder (
TripSearch.Builder). Holds the in-progress values, exposes one method per field or step (each returning the builder, for chaining) and abuild()method that validates and creates the product. - Concrete builders (GoF form only). Several implementations of one builder interface, each producing a different representation from the same steps.
- Director (GoF form only, optional). Knows the order of construction steps and drives a builder through them. The client chooses the builder, and the director doesn't care which one it is.
- Client. Creates the builder, sets what it needs and calls
build()(or asks a director to drive it, then fetches the result from the builder).
Implementation
The three versions below implement the same rules. The required fields go in the builder's constructor (or factory), optional fields have defaults, and build() checks every rule and returns an immutable product. Each also offers toBuilder() so you can derive a modified copy without touching the original.
import java.time.LocalDate;
import java.util.*;
enum Cabin { ECONOMY, PREMIUM, BUSINESS, FIRST }
final class TripSearch {
private final String from, to;
private final LocalDate depart, returnDate; // returnDate may be null (one-way)
private final int passengers, maxStops;
private final Cabin cabin;
private final boolean flexibleDates;
private final List<String> excludedAirlines;
private TripSearch(Builder b) {
from = b.from; to = b.to; depart = b.depart; returnDate = b.returnDate;
passengers = b.passengers; maxStops = b.maxStops; cabin = b.cabin;
flexibleDates = b.flexibleDates;
excludedAirlines = List.copyOf(b.excludedAirlines); // defensive, immutable copy
}
// Required fields up front: you can't even get a builder without them.
static Builder builder(String from, String to, LocalDate depart) { return new Builder(from, to, depart); }
Builder toBuilder() {
Builder b = new Builder(from, to, depart)
.passengers(passengers).cabin(cabin).maxStops(maxStops).flexibleDates(flexibleDates);
if (returnDate != null) b.returnOn(returnDate);
excludedAirlines.forEach(b::excludeAirline);
return b;
}
String from() { return from; }
Optional<LocalDate> returnDate() { return Optional.ofNullable(returnDate); }
int passengers() { return passengers; }
Cabin cabin() { return cabin; }
List<String> excludedAirlines() { return excludedAirlines; }
static final class Builder {
private final String from, to;
private final LocalDate depart;
private LocalDate returnDate;
private int passengers = 1;
private int maxStops = 2;
private Cabin cabin = Cabin.ECONOMY;
private boolean flexibleDates;
private final List<String> excludedAirlines = new ArrayList<>();
private Builder(String from, String to, LocalDate depart) {
this.from = Objects.requireNonNull(from, "from");
this.to = Objects.requireNonNull(to, "to");
this.depart = Objects.requireNonNull(depart, "depart");
}
Builder returnOn(LocalDate date) { this.returnDate = Objects.requireNonNull(date); return this; }
Builder passengers(int n) { this.passengers = n; return this; }
Builder cabin(Cabin c) { this.cabin = Objects.requireNonNull(c); return this; }
Builder maxStops(int n) { this.maxStops = n; return this; }
Builder flexibleDates(boolean f) { this.flexibleDates = f; return this; }
Builder excludeAirline(String code) { this.excludedAirlines.add(code); return this; }
TripSearch build() {
List<String> errors = new ArrayList<>();
if (from.equals(to)) errors.add("origin and destination must differ");
if (returnDate != null && returnDate.isBefore(depart)) errors.add("return is before departure");
if (passengers < 1 || passengers > 9) errors.add("passengers must be 1-9, got " + passengers);
if (maxStops < 0) errors.add("maxStops must be >= 0");
if (!errors.isEmpty()) throw new IllegalStateException(String.join("; ", errors));
return new TripSearch(this);
}
}
}
public class Main {
public static void main(String[] args) {
LocalDate out = LocalDate.of(2026, 12, 20), back = LocalDate.of(2026, 12, 27);
TripSearch s = TripSearch.builder("DEL", "BOM", out)
.returnOn(back)
.passengers(2)
.cabin(Cabin.BUSINESS)
.excludeAirline("XX")
.build();
if (s.passengers() != 2 || s.cabin() != Cabin.BUSINESS) throw new AssertionError("fields");
// Immutable: the list can't be changed through the product.
try { s.excludedAirlines().add("YY"); throw new AssertionError("list is mutable"); }
catch (UnsupportedOperationException expected) { }
// Derive a variant without touching the original.
TripSearch family = s.toBuilder().passengers(4).cabin(Cabin.ECONOMY).build();
if (family.passengers() != 4 || s.passengers() != 2) throw new AssertionError("toBuilder");
// All rule violations are reported together.
try {
TripSearch.builder("DEL", "DEL", back).returnOn(out).passengers(0).build();
throw new AssertionError("should have failed");
} catch (IllegalStateException e) {
if (!e.getMessage().contains("differ") || !e.getMessage().contains("before")
|| !e.getMessage().contains("1-9")) throw new AssertionError(e.getMessage());
}
System.out.println("built, derived and rejected as expected");
}
}
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date
from enum import Enum
class Cabin(Enum):
ECONOMY = "economy"
PREMIUM = "premium"
BUSINESS = "business"
FIRST = "first"
@dataclass(frozen=True)
class TripSearch:
origin: str
destination: str
depart: date
return_date: date | None
passengers: int
cabin: Cabin
max_stops: int
excluded_airlines: tuple[str, ...]
@staticmethod
def builder(origin: str, destination: str, depart: date) -> TripSearchBuilder:
return TripSearchBuilder(origin, destination, depart)
def to_builder(self) -> TripSearchBuilder:
b = TripSearchBuilder(self.origin, self.destination, self.depart)
b._return_date, b._passengers, b._cabin = self.return_date, self.passengers, self.cabin
b._max_stops, b._excluded = self.max_stops, list(self.excluded_airlines)
return b
@dataclass
class TripSearchBuilder:
_origin: str
_destination: str
_depart: date
_return_date: date | None = None
_passengers: int = 1
_cabin: Cabin = Cabin.ECONOMY
_max_stops: int = 2
_excluded: list[str] = field(default_factory=list)
def return_on(self, d: date) -> TripSearchBuilder:
self._return_date = d
return self
def passengers(self, n: int) -> TripSearchBuilder:
self._passengers = n
return self
def cabin(self, c: Cabin) -> TripSearchBuilder:
self._cabin = c
return self
def exclude_airline(self, code: str) -> TripSearchBuilder:
self._excluded.append(code)
return self
def build(self) -> TripSearch:
errors = []
if self._origin == self._destination:
errors.append("origin and destination must differ")
if self._return_date and self._return_date < self._depart:
errors.append("return is before departure")
if not 1 <= self._passengers <= 9:
errors.append(f"passengers must be 1-9, got {self._passengers}")
if errors:
raise ValueError("; ".join(errors))
return TripSearch(self._origin, self._destination, self._depart, self._return_date,
self._passengers, self._cabin, self._max_stops, tuple(self._excluded))
out, back = date(2026, 12, 20), date(2026, 12, 27)
s = (TripSearch.builder("DEL", "BOM", out)
.return_on(back).passengers(2).cabin(Cabin.BUSINESS).exclude_airline("XX").build())
assert s.passengers == 2 and s.excluded_airlines == ("XX",)
family = s.to_builder().passengers(4).build()
assert family.passengers == 4 and s.passengers == 2
try:
TripSearch.builder("DEL", "DEL", back).return_on(out).passengers(0).build()
raise AssertionError("should have failed")
except ValueError as e:
assert "differ" in str(e) and "before" in str(e) and "1-9" in str(e)
print("built, derived and rejected as expected")
import assert from "node:assert/strict";
type Cabin = "economy" | "premium" | "business" | "first";
class TripSearch {
private constructor(
readonly from: string,
readonly to: string,
readonly depart: Date,
readonly returnDate: Date | undefined,
readonly passengers: number,
readonly cabin: Cabin,
readonly maxStops: number,
readonly excludedAirlines: readonly string[],
) {
Object.freeze(this);
}
static builder(from: string, to: string, depart: Date): TripSearch.Builder {
return new TripSearch.Builder(from, to, depart);
}
toBuilder(): TripSearch.Builder {
const b = new TripSearch.Builder(this.from, this.to, this.depart)
.passengers(this.passengers).cabin(this.cabin).maxStops(this.maxStops);
if (this.returnDate) b.returnOn(this.returnDate);
this.excludedAirlines.forEach((a) => b.excludeAirline(a));
return b;
}
static Builder = class Builder {
#returnDate: Date | undefined;
#passengers = 1;
#cabin: Cabin = "economy";
#maxStops = 2;
#excluded: string[] = [];
constructor(private readonly from: string, private readonly to: string, private readonly depart: Date) {}
returnOn(d: Date): this { this.#returnDate = d; return this; }
passengers(n: number): this { this.#passengers = n; return this; }
cabin(c: Cabin): this { this.#cabin = c; return this; }
maxStops(n: number): this { this.#maxStops = n; return this; }
excludeAirline(code: string): this { this.#excluded.push(code); return this; }
build(): TripSearch {
const errors: string[] = [];
if (this.from === this.to) errors.push("origin and destination must differ");
if (this.#returnDate && this.#returnDate < this.depart) errors.push("return is before departure");
if (!Number.isInteger(this.#passengers) || this.#passengers < 1 || this.#passengers > 9)
errors.push(`passengers must be 1-9, got ${this.#passengers}`);
if (errors.length) throw new Error(errors.join("; "));
// The builder is nested inside the class, so it may call the private constructor.
return new TripSearch(this.from, this.to, this.depart, this.#returnDate, this.#passengers,
this.#cabin, this.#maxStops, Object.freeze([...this.#excluded]));
}
};
}
declare namespace TripSearch {
type Builder = InstanceType<typeof TripSearch.Builder>;
}
const out = new Date("2026-12-20"), back = new Date("2026-12-27");
const s = TripSearch.builder("DEL", "BOM", out).returnOn(back).passengers(2).cabin("business").excludeAirline("XX").build();
assert.equal(s.passengers, 2);
assert.ok(Object.isFrozen(s) && Object.isFrozen(s.excludedAirlines));
const family = s.toBuilder().passengers(4).build();
assert.equal(family.passengers, 4);
assert.equal(s.passengers, 2);
assert.throws(
() => TripSearch.builder("DEL", "DEL", back).returnOn(out).passengers(0).build(),
(e: Error) => e.message.includes("differ") && e.message.includes("before") && e.message.includes("1-9"),
);
console.log("built, derived and rejected as expected");
Design decisions worth explaining in an interview:
- Required fields go in the builder's constructor.
TripSearch.builder("DEL", "BOM", out)can't be called without them, so the compiler enforces "required" for the fields that matter most. Optional fields get defaults in the builder. build()validates the whole object at once, and reports every violation rather than the first. Cross-field rules ("return after departure") can only be checked here, once all fields are known.- The product is immutable, with defensive copies of collections (
List.copyOf,tuple(...),Object.freeze([...])). If the builder's list were passed straight through, adding to the builder afterbuild()would change an already-built product. - The builder is mutable and not thread-safe, and that's fine. It's meant to be used by one thread, briefly, then thrown away. The product is what gets shared.
toBuilder()gives you "copy with changes" without setters on the product. This is the builder's answer to the "wither" methods (withPassengers(4)) you'd otherwise write by hand.
Required versus optional fields: three strategies
There are three common ways to make sure required fields are set, with different trade-offs:
| Strategy | How | When a field is missing | Cost |
|---|---|---|---|
| Builder constructor | builder(from, to, depart) | Compile error | Back to positional arguments for the required ones, so keep there few and of different types |
Validate in build() | Check for null and throw | Run-time error at build() | Easy, flexible, but errors move from compile time to run time |
| Step builder | A chain of interfaces, each exposing only the next required step | Compile error, and the IDE guides you | More types to write and maintain |
Step builders: making the compiler enforce order
A step builder (sometimes called a type-safe or staged builder) returns a different interface after each required step, and only the final interface has build(). You literally can't call build() until every required step has happened, and code completion shows exactly one next step at a time.
import java.time.LocalDate;
record Search(String from, String to, LocalDate depart, int passengers) {}
final class SearchSteps {
interface FromStep { ToStep from(String airport); }
interface ToStep { DepartStep to(String airport); }
interface DepartStep { OptionalStep departing(LocalDate date); }
interface OptionalStep {
OptionalStep passengers(int n);
Search build();
}
static FromStep start() { return new Impl(); }
// One class implements every step; callers only ever see the narrow interfaces.
private static final class Impl implements FromStep, ToStep, DepartStep, OptionalStep {
private String from, to;
private LocalDate depart;
private int passengers = 1;
public ToStep from(String airport) { this.from = airport; return this; }
public DepartStep to(String airport) { this.to = airport; return this; }
public OptionalStep departing(LocalDate date) { this.depart = date; return this; }
public OptionalStep passengers(int n) { this.passengers = n; return this; }
public Search build() {
if (passengers < 1 || passengers > 9) throw new IllegalStateException("passengers must be 1-9");
return new Search(from, to, depart, passengers);
}
}
}
public class Main {
public static void main(String[] args) {
Search s = SearchSteps.start().from("DEL").to("BOM").departing(LocalDate.of(2026, 12, 20)).passengers(3).build();
if (s.passengers() != 3 || !s.to().equals("BOM")) throw new AssertionError(s);
// SearchSteps.start().from("DEL").build(); // does not compile: ToStep has no build()
System.out.println(s);
}
}
# Python has no compile step, but a type checker (mypy, pyright) enforces the same
# staging statically, and at run time the missing methods raise AttributeError.
from dataclasses import dataclass
from datetime import date
@dataclass(frozen=True)
class Search:
origin: str
destination: str
depart: date
passengers: int = 1
class _Optional:
def __init__(self, origin: str, destination: str, depart: date) -> None:
self._args = (origin, destination, depart)
self._passengers = 1
def passengers(self, n: int) -> "_Optional":
self._passengers = n
return self
def build(self) -> Search:
if not 1 <= self._passengers <= 9:
raise ValueError("passengers must be 1-9")
return Search(*self._args, passengers=self._passengers)
class _Depart:
def __init__(self, origin: str, destination: str) -> None:
self._o, self._d = origin, destination
def departing(self, d: date) -> _Optional:
return _Optional(self._o, self._d, d)
class _To:
def __init__(self, origin: str) -> None:
self._o = origin
def to(self, airport: str) -> _Depart:
return _Depart(self._o, airport)
class SearchSteps:
@staticmethod
def from_(airport: str) -> _To:
return _To(airport)
s = SearchSteps.from_("DEL").to("BOM").departing(date(2026, 12, 20)).passengers(3).build()
assert s == Search("DEL", "BOM", date(2026, 12, 20), 3)
assert not hasattr(SearchSteps.from_("DEL"), "build") # no build() before the required steps
print(s)
import assert from "node:assert/strict";
type Search = Readonly<{ from: string; to: string; depart: Date; passengers: number }>;
interface FromStep { from(airport: string): ToStep }
interface ToStep { to(airport: string): DepartStep }
interface DepartStep { departing(date: Date): OptionalStep }
interface OptionalStep { passengers(n: number): OptionalStep; build(): Search }
function searchBuilder(): FromStep {
const draft = { from: "", to: "", depart: new Date(0), passengers: 1 };
const optional: OptionalStep = {
passengers(n) { draft.passengers = n; return optional; },
build() {
if (draft.passengers < 1 || draft.passengers > 9) throw new Error("passengers must be 1-9");
return Object.freeze({ ...draft });
},
};
return {
from: (a) => { draft.from = a; return {
to: (b) => { draft.to = b; return {
departing: (d) => { draft.depart = d; return optional; },
}; },
}; },
};
}
const s = searchBuilder().from("DEL").to("BOM").departing(new Date("2026-12-20")).passengers(3).build();
assert.equal(s.passengers, 3);
assert.equal(s.to, "BOM");
// @ts-expect-error: build() is not available until the required steps are done
searchBuilder().from("DEL").build;
console.log(s);
Step builders shine in public library APIs, where the IDE-guided "one valid next step" is worth the extra types. In application code, a constructor for the required fields plus validation in build() is usually enough.
The GoF form: one process, several representations
The original Builder is about a different problem: the same sequence of construction steps should produce different outputs. A trip planner assembles an itinerary from flights and hotels. The director knows the order and the rules (flights before the hotel on arrival day, for example). Each builder turns those steps into a different representation: a printable summary, calendar entries, or a JSON payload.
import java.util.*;
interface ItineraryBuilder {
void addFlight(String from, String to, String day);
void addHotel(String city, String checkIn, int nights);
}
final class TextItinerary implements ItineraryBuilder {
private final StringBuilder out = new StringBuilder();
public void addFlight(String from, String to, String day) { out.append(day).append(": fly ").append(from).append(" -> ").append(to).append('\n'); }
public void addHotel(String city, String checkIn, int nights) { out.append(checkIn).append(": hotel in ").append(city).append(", ").append(nights).append(" nights\n"); }
String result() { return out.toString(); }
}
final class CalendarItinerary implements ItineraryBuilder {
record Event(String day, String title) {}
private final List<Event> events = new ArrayList<>();
public void addFlight(String from, String to, String day) { events.add(new Event(day, "Flight " + from + "-" + to)); }
public void addHotel(String city, String checkIn, int nights) { events.add(new Event(checkIn, "Check in: " + city)); }
List<Event> result() { return List.copyOf(events); }
}
// The director owns the construction sequence and knows nothing about output formats.
final class RoundTripDirector {
void construct(ItineraryBuilder b, String home, String away, String outDay, String backDay, int nights) {
b.addFlight(home, away, outDay);
b.addHotel(away, outDay, nights);
b.addFlight(away, home, backDay);
}
}
public class Main {
public static void main(String[] args) {
RoundTripDirector director = new RoundTripDirector();
TextItinerary text = new TextItinerary();
CalendarItinerary calendar = new CalendarItinerary();
director.construct(text, "DEL", "GOI", "Dec 20", "Dec 27", 7);
director.construct(calendar, "DEL", "GOI", "Dec 20", "Dec 27", 7);
if (!text.result().startsWith("Dec 20: fly DEL -> GOI")) throw new AssertionError(text.result());
if (calendar.result().size() != 3) throw new AssertionError(calendar.result());
System.out.print(text.result());
}
}
Notice that result() isn't on the builder interface. Each representation has a different type (String, List<Event>), so the client fetches the result from the concrete builder it chose. That's straight from the original pattern description, and it's a detail interviewers occasionally ask about. In everyday code the GoF form is rarer than the fluent builder, but you'll recognise it in document converters, in compilers (a parser driving different tree or bytecode builders) and in SAX-style XML parsing, where the parser plays director and your handler is the builder.
Idiomatic alternatives: records, dataclasses and options objects
Builder exists largely to work around languages without named arguments or default values. Python and TypeScript have both, and modern Java has records. Before writing a builder, check whether the language already solves the problem.
import java.time.LocalDate;
import java.util.List;
// A record with a compact constructor: immutable, validated, and short.
// Fine when there are only a few fields and they have distinct types.
record TripSearch(String from, String to, LocalDate depart, LocalDate returnDate, int passengers,
List<String> excludedAirlines) {
TripSearch {
if (from.equals(to)) throw new IllegalArgumentException("origin and destination must differ");
if (returnDate != null && returnDate.isBefore(depart)) throw new IllegalArgumentException("return before departure");
if (passengers < 1 || passengers > 9) throw new IllegalArgumentException("passengers must be 1-9");
excludedAirlines = List.copyOf(excludedAirlines); // defensive copy, still immutable
}
// Static factories for the common shapes stand in for optional parameters.
static TripSearch oneWay(String from, String to, LocalDate depart) {
return new TripSearch(from, to, depart, null, 1, List.of());
}
// A hand-written "wither" for the field that changes most.
TripSearch withPassengers(int n) {
return new TripSearch(from, to, depart, returnDate, n, excludedAirlines);
}
}
public class Main {
public static void main(String[] args) {
TripSearch s = TripSearch.oneWay("DEL", "BOM", LocalDate.of(2026, 12, 20)).withPassengers(2);
if (s.passengers() != 2 || s.returnDate() != null) throw new AssertionError(s);
try {
new TripSearch("DEL", "DEL", LocalDate.of(2026, 12, 20), null, 1, List.of());
throw new AssertionError("should have failed");
} catch (IllegalArgumentException expected) { }
System.out.println(s);
}
}
from dataclasses import dataclass, field, replace
from datetime import date
# kw_only=True: every field must be passed by name, so arguments can't be swapped.
# frozen=True: immutable. __post_init__: validation across fields.
@dataclass(frozen=True, kw_only=True)
class TripSearch:
origin: str
destination: str
depart: date
return_date: date | None = None
passengers: int = 1
cabin: str = "economy"
max_stops: int = 2
excluded_airlines: tuple[str, ...] = field(default=())
def __post_init__(self) -> None:
errors = []
if self.origin == self.destination:
errors.append("origin and destination must differ")
if self.return_date and self.return_date < self.depart:
errors.append("return is before departure")
if not 1 <= self.passengers <= 9:
errors.append("passengers must be 1-9")
if errors:
raise ValueError("; ".join(errors))
s = TripSearch(origin="DEL", destination="BOM", depart=date(2026, 12, 20),
return_date=date(2026, 12, 27), passengers=2, cabin="business")
family = replace(s, passengers=4) # the toBuilder() equivalent, and it re-validates
assert family.passengers == 4 and s.passengers == 2
try:
replace(s, passengers=0)
raise AssertionError("should have failed")
except ValueError as e:
assert "1-9" in str(e)
try:
TripSearch("DEL", "BOM", date(2026, 12, 20)) # type: ignore[misc]
raise AssertionError("positional arguments should be rejected")
except TypeError:
pass
print(s)
import assert from "node:assert/strict";
type Cabin = "economy" | "premium" | "business" | "first";
// Required fields are required properties; optional ones are `?`.
interface TripSearchOptions {
from: string;
to: string;
depart: Date;
returnDate?: Date;
passengers?: number;
cabin?: Cabin;
maxStops?: number;
}
type TripSearch = Readonly<Required<Omit<TripSearchOptions, "returnDate">> & { returnDate?: Date }>;
function tripSearch({ passengers = 1, cabin = "economy", maxStops = 2, ...rest }: TripSearchOptions): TripSearch {
const errors: string[] = [];
if (rest.from === rest.to) errors.push("origin and destination must differ");
if (rest.returnDate && rest.returnDate < rest.depart) errors.push("return is before departure");
if (!Number.isInteger(passengers) || passengers < 1 || passengers > 9) errors.push("passengers must be 1-9");
if (errors.length) throw new Error(errors.join("; "));
return Object.freeze({ ...rest, passengers, cabin, maxStops });
}
const s = tripSearch({ from: "DEL", to: "BOM", depart: new Date("2026-12-20"), passengers: 2, cabin: "business" });
const family = tripSearch({ ...s, passengers: 4 }); // copy with changes, re-validated
assert.equal(family.passengers, 4);
assert.equal(s.passengers, 2);
assert.throws(() => tripSearch({ from: "DEL", to: "DEL", depart: new Date("2026-12-20") }), /differ/);
// @ts-expect-error: a missing required field is a compile error
tripSearch({ from: "DEL", depart: new Date("2026-12-20") });
console.log(s);
How these compare with a builder:
- Python
@dataclass(frozen=True, kw_only=True)gives named arguments, defaults, immutability and__post_init__validation.dataclasses.replaceistoBuilder()with re-validation built in. For most Python code this is strictly better than a builder class. Pydantic models andattrsclasses offer the same with more validation features. - TypeScript options objects give named fields, compile-time required/optional checking, defaults through destructuring, and copy-with-changes through spread. They're the norm in JavaScript APIs, from
fetch(url, { method, headers })to Node'sfs.writeFile(path, data, { encoding }). - Java records are excellent for small value objects, but they're still positional. Once a record has more than four or five parameters, or several of the same type, call sites become as unreadable as the telescoping constructor. That's the point to add a builder. Java has no built-in "copy with changes" for records. Derived record creation (
withexpressions) has been proposed (JEP 468) but isn't part of the language as of Java 24, so hand-written withers or a builder fill the gap.
Lombok
Many Java codebases generate builders with Lombok. @Builder on a class or record generates the builder, @Builder(toBuilder = true) adds toBuilder(), @Singular generates addX/clearX methods for collections, and @Builder.Default sets field defaults. It removes the duplication cost, but it doesn't validate anything unless you write that validation yourself (for example in the constructor that Lombok's builder calls). It also hides the generated code from readers who don't know Lombok. Treat it as a typing aid, not as a design.
Real-world uses
JDK
java.net.http.HttpClient.newBuilder()andHttpRequest.newBuilder(uri): fluent builders that produce immutable clients and requests.ProcessBuilder: configures a command, working directory, environment and redirects, thenstart()launches the process. Unusually, the builder is reusable, so you can start several processes from one.Locale.Builder,Calendar.Builder,Stream.builder()andDateTimeFormatterBuilder.StringBuilderis a builder in the everyday sense (accumulate, thentoString()), though it's more of a mutable buffer than a GoF builder.
Spring
UriComponentsBuilderbuilds and encodes URIs.ResponseEntity.ok().header(...).body(...)andResponseEntity.status(...)are builders for HTTP responses.WebClient.builder()andRestClient.builder()configure HTTP clients. Spring Security's configuration DSL (http.authorizeHttpRequests(...)) is builder-style throughout.
.NET
WebApplication.CreateBuilder(args)returns a builder for services, configuration and logging.Build()then produces the immutableWebApplication.ConfigurationBuilder,HostBuilder,UriBuilderandStringBuilderfollow the same idea.
Libraries across languages
- Protocol Buffers generate a builder for every message in Java (
Person.newBuilder().setName(...).build()), and messages are immutable. - OkHttp's
Request.Builder, Guava'sImmutableList.builder(), and the query builders in Knex (Node) and SQLAlchemy Core (Python), whereselect(users).where(...).order_by(...)returns a new statement at each step instead of mutating one.
Python standard library
- Python rarely needs builders because of keyword arguments.
argparse.ArgumentParseris builder-like (calladd_argumentrepeatedly, thenparse_args). Theemail.message.EmailMessageAPI is also assembled step by step before being serialised.
When NOT to use it, and the costs
- Few fields with distinct types. A constructor or record with three parameters of different types is already readable. A builder doubles the code for no benefit.
- The language already has named arguments and defaults. In Python and TypeScript (and Kotlin, C#, Swift), keyword arguments or options objects cover nearly everything a builder does. Builders still have a place there for multi-step assembly (query builders), but not for "many optional fields".
- The builder doesn't validate. If
build()only copies fields, you've written a verbose constructor. The value is in enforcing required fields, cross-field rules and immutability. - The object is meant to be mutable anyway. If the product has setters, the builder adds a second way to set the same fields.
- Fields change often. Every new field must be added to the product, the builder,
build()andtoBuilder(). ForgettingtoBuilder()is a classic bug, because copies silently lose the new field.
Costs:
| Cost | Why it matters |
|---|---|
| Duplication | Each field exists in the product, the builder and the copy logic |
| Errors move to run time | Unless required fields are in the builder constructor or a step builder |
| Allocation | One extra object per construction (rarely significant) |
| Discoverability | Readers must learn which fields are required, unless the API makes it obvious |
Related patterns and how they differ
- Abstract Factory. Returns each product immediately and focuses on keeping a family of products consistent. Builder assembles one complex product over several steps and returns it at the end.
- Factory Method. Decides which class to create. Builder decides how to assemble an instance. They combine naturally:
HttpRequest.newBuilder()is a static factory method returning a builder. - Prototype. Creates new objects by copying an existing one.
toBuilder()gives a similar "start from this and change a bit" ability while keeping validation in one place. - Composite. Builders often construct composite trees: document builders, UI trees and query ASTs. The builder hides the tree-assembly details from the client.
- Template Method. A GoF director is a fixed sequence of steps applied to an interchangeable builder. It's similar in spirit to a template method, but uses composition instead of inheritance.
- Fluent interface. Method chaining that returns
this. Builders usually use a fluent interface, but a fluent interface isn't necessarily a builder: stream pipelines and SQLAlchemy queries are fluent without producing an immutable product at a separatebuild()step.
The smell that suggests it
- Telescoping constructors, or one constructor with more than about four parameters, especially several of the same type.
- Call sites full of
null,0,falseor""passed only to reach a later parameter. - Objects that exist in an invalid state between construction and a series of setter calls, often with an
init()orvalidate()method that callers must remember to call. - Boolean parameters whose meaning is invisible at the call site (
new Report(data, true, false)). - Test code that builds the same complex object with small variations many times. A test-data builder (
aTrip().withPassengers(4).build()) is one of the most valuable uses of the pattern, even in languages with named arguments, because it encodes sensible defaults for tests.
Interview questions
- "Why use a builder instead of a constructor?" Readability with many parameters, especially optional or same-typed ones; validation of the whole object, including cross-field rules, at one point; and immutable products without a half-built phase. Mention that with three or four distinct-typed fields, a constructor is better.
- "How do you handle required fields in a builder?" Put them in the builder's constructor or factory (compile-time check), validate them in
build()(run-time check) or use a step builder where each required step returns the next interface and only the last one exposesbuild(). - "How do you make the product immutable?"
finalfields, no setters, a private constructor taking the builder, and defensive copies of mutable inputs such as lists (List.copyOf). Without the copy, mutating the builder afterbuild()changes the product. - "Is a builder thread-safe?" Usually not, and it doesn't need to be: one thread uses it briefly. The immutable product is safe to share. If a builder is shared between threads, that's a design smell.
- "What's the difference between the GoF Builder and the Effective Java builder?" GoF separates a construction process (the director) from the representation, so the same steps produce different products. The Effective Java builder replaces telescoping constructors with a fluent, validated way to make one immutable class.
- "How would you do this in Python or TypeScript?" Python: a frozen, keyword-only dataclass with
__post_init__validation, anddataclasses.replacefor copies. TypeScript: an options object type with required and optional properties, defaults through destructuring, andObject.freeze. A builder is still useful for multi-step assembly such as query construction. - "What does Lombok's
@Buildergive you and what doesn't it?" It generates the builder class, fluent setters,build(), optionallytoBuilder()and singular collection methods. It doesn't validate, and it hides code from readers. Put validation in the constructor the builder calls. - "Where would you use a builder in an LLD interview?" For a configuration-heavy object: a search or filter query, a notification with optional channels and attachments, a pizza or burger order with options, or a game setup with optional rules. Keep it small and say what
build()validates. That's what earns credit.
Further reading
- Creational Patterns: the grouped overview with a query builder and a Go builder.
- Prototype: copying objects, and how it relates to
toBuilder(). - Common LLD Mistakes: when a builder is over-engineering.
- Design Patterns: One Page Each: the index of every pattern page.