Pattern 13/22 · Creational
Builder
Construct an object with many parameters (mostly optional) through an intermediate object that accumulates them step by step, then commit in build() — the one place that validates every constraint and produces a final object that is guaranteed to be valid.
01 — It starts with code that is breaking
Problem
Your slider component has 8 settings: width, step, disabled, showTicks, trackColor, value, min, max. On the first morning, you write:
The Builder problem starts with a line of code that looks harmless, and it breaks in a very specific way. Call new Slider(300, 20, true, false, "#000", 1) and the reader has to open the constructor to learn what true is, what false is, and whether 1 is the value or the min. Worse: two booleans sit side by side, swap them and the code still runs, still type-checks green — the only difference is that the ticks are hidden and the slider is disabled. No test catches it, because nobody thinks of it as a bug.
TypeScript won't save you here, and it's worth being clear about why: the compiler checks order and type, and here the types are the same. Swap two numbers, swap two strings — all valid. A constructor with many same-typed parameters is a built-in blind spot of every language with positional arguments.
The fix everyone reaches for: an options object. new Slider({ width: 300, step: 20, disabled: true, trackColor: "#000" }) with defaults for whatever is missing. The readability problem disappears instantly, and I'll say it plainly: 80% of "we need a Builder" cases end right here, and they should.
But then the invariants show up. min must be less than max; value must lie within [min, max]; step must divide the range evenly; precision and format are free to contradict each other; logarithmic: true is valid with min > 0 but not with min = 0. An options object lets you construct an invalid object anywhere in the codebase. Cram all the validation into the constructor and you get a different problem: every field has to arrive at once, while the config team builds min/max from a theme file and the data-sync job assigns value later.
And some objects have no single "moment" at which to validate. An HTTP client: set the baseURL, then headers, then timeout, then sign the request, then send — after sending, no more changes allowed. A query builder: from first, then where, then orderBy, then limit, then execute. An options literal has no notion of "when" or "what may be called after what". Builder exists for exactly two things: cross-field constraints, and construction that happens over multiple steps.
02 — The idea, before touching code
Solution
Split it into two objects. The Builder: mutable, allowed to be in an invalid state, with one job — collecting configuration. The Product (Slider): readonly, can't be constructed from outside, and every instance of it is guaranteed to be valid. The only bridge between the two worlds is build(), and that's where you put all the validation — once, as close as possible to where it gets violated.
Setters return this so you can read the configuration like a sentence: new SliderBuilder().min(0).max(100).step(5).value(20).build(). Each setter can also hold its own local rule (step(-1) dies right at the call site, instead of dying in build() 20 chained calls later), while build() handles the cross-field constraints that no single setter can know about.
The rest of this page is about not using Builder. Because in TypeScript, builder is the most commonly misused pattern in the creational family: it looks professional, it's fun to write, and its cost (long-lived mutable state, an extra object, an extra layer of indirection) is a hidden cost — you only feel it when debugging. If your product has no cross-field constraints and no multi-stage construction, the 12-line function in the last step is the right version. Builder is a tool for invariants, not a tool for "lots of parameters".
03 — Doing it for real, one code fragment per step
Step by step
Write the disaster version, and point at exactly two bugs
This is the real starting point of most sliders, tooltips, and table configs:
class Slider {
constructor(
width: number, step: number, disabled: boolean,
showTicks: boolean, trackColor: string, value: number,
min: number, max: number,
) { /* ... */ }
}
const a = new Slider(300, 20, true, false, "#000", 1, 0, 100)
const b = new Slider(300, 20, false, true, "#000", 1, 0, 100) // intended
// The real bug: in file #47, someone put value before min:
const c = new Slider(300, 20, false, true, "#000", 0, 1, 100)c builds a slider with value=0 and min=1 — valid to TS, meaningless to the user.Options object + defaults: no more blind parameters, and usually enough
Before building a builder, do this step. One parameter object, required fields on their own, optional ones with defaults:
interface SliderOpts {
min: number // required: TS forces you to pass it
max: number
step?: number
value?: number
disabled?: boolean
showTicks?: boolean
trackColor?: string
}
const DEFAULTS = { step: 1, value: 0, disabled: false, showTicks: true, trackColor: "#888" }
class Slider {
constructor(opts: SliderOpts) {
const o = { ...DEFAULTS, ...opts }
// ...
}
}List the invariants — the make-or-break question for this pattern
Grab a piece of paper and write down every rule of the form "field A relates to field B". Here's the real list for a slider after 6 months in production:
1. min < max
2. min <= value <= max
3. (max - min) is divisible by step
4. logarithmic => min > 0
5. precision only makes sense when format = "number"
6. custom format => must have a formatter, and vice versa
7. disabled => value is locked (can't be set afterwards)
=> There are CROSS-FIELD constraints = Builder is justified.
=> Only per-field defaults = an options object is enough.Separate the accumulating part from the immutable part
Two classes, two fates. The Builder is mutable and allowed to be invalid — that's a feature, not a bug: it's where you hold the half-built state. The Product is readonly and can only come out of one door.
class Slider {
constructor(
readonly min: number,
readonly max: number,
readonly step: number,
readonly value: number,
) {}
// No setters. Want a change? Build a new one.
}
class SliderBuilder {
#min = 0
#max = 100
#step = 1
#value = 0
// Intermediate state: does NOT need to be valid yet.
}Slider, every rule from step 3 already holds — no need to check again.Setters return this, and each setter owns its local rule
Fluent isn't about looking pretty: it lets a long configuration read like a sentence, and it gives you the right to fail early on local rules. step(-1) is wrong on its own, no other field needed — block it right in the setter and report the error at the calling line:
class SliderBuilder {
#min = 0
#max = 100
#step = 1
min(v: number) { this.#min = v; return this }
max(v: number) { this.#max = v; return this }
step(v: number) {
if (v <= 0) throw new Error("step must be greater than 0") // single-field rule
this.#step = v
return this
}
}build() because only then do you have all the data.build() is the only gate, and the place for real validation
All cross-field validation lives here, ordered from the most common error down. This is also where you apply the last defaults and cut off meaningless combinations:
class SliderBuilder {
// ... fields and setters from the previous step
build(): Slider {
if (this.#min >= this.#max) throw new Error("min must be less than max")
if (this.#value < this.#min || this.#value > this.#max)
throw new Error("value " + this.#value + " is outside [" + this.#min + ", " + this.#max + "]")
if ((this.#max - this.#min) % this.#step !== 0)
throw new Error("step " + this.#step + " does not evenly divide the range " + (this.#max - this.#min))
return Slider.from({ min: this.#min, max: this.#max, step: this.#step, value: this.#value })
}
}Type-state: when the order of steps is itself a rule
For some builders the order is the business logic: where is meaningless before from; once a request has been send()-ed you can't setHeader() anymore. Runtime validation only catches that after someone runs the tests. Type-state catches it while you write the code, by making a method exist on the type or not depending on the state:
class SelectQ<HasFrom = false> {
#sql: string[] = []
from(this: SelectQ<false>, table: string): SelectQ<true> {
this.#sql.push("from " + table)
return this as SelectQ<true>
}
where(this: SelectQ<true>, cond: string): SelectQ<true> {
this.#sql.push("where " + cond)
return this
}
execute(this: SelectQ<true>): string { return this.#sql.join(" ") }
}
new SelectQ().from("user").where("id = 1").execute() // OK
new SelectQ().where("id = 1") // compile errorthis:. Kysely and other typed query builders use variants of exactly this technique.The 12-line version, and four questions before you commit
This is the part most articles about Builder leave out. Most "builders" in real TS projects are really a pure function + an assert function, and that version is better because it has no state, no extra allocation, and you can read all of it in 12 lines:
type SliderOpts = { min: number, max: number, step?: number, value?: number }
function assertValid(o: Required<SliderOpts>) {
if (o.min >= o.max) throw new Error("min must be less than max")
if (o.value < o.min || o.value > o.max) throw new Error("value out of range")
if ((o.max - o.min) % o.step !== 0) throw new Error("step does not evenly divide the range")
}
export function buildSlider(opts: SliderOpts): Slider {
const o = { step: 1, value: opts.min, ...opts } as Required<SliderOpts>
assertValid(o)
return new Slider(o.min, o.max, o.step, o.value)
}04 — Who talks to whom
Structure
- BuilderHolds mutable configuration, exposes setters that return `this`, allows invalid intermediate state.
- Product (Slider)Readonly, no setters, reachable **only** through `build()`. Every instance of it is valid.
- DirectorGoF has one (a fixed construction procedure). In JS/TS it barely exists — if you're writing a Director, you're usually rewriting a function.
- ClientChains setters, then calls `build()`. After that the client holds only the Product, never the Builder.
- ValidatorNot a class, but the real protagonist: the set of cross-field rules that lives in `build()` (or in a separate `parse()`).
Client
│ new SliderBuilder().min(0).max(100).step(5).value(20)
▼
┌────────────────────────────────┐
│ SliderBuilder (MUTABLE) │ INVALID state: allowed
│ #min #max #step #value │
│ + min(v): this │
│ + build(): Slider │ <- cross-field validation, once
└───────────────┬────────────────┘
│ the only thing allowed to create a Slider
▼
┌──────────────────────────────┐
│ Slider (READONLY) │ already valid, can't be changed
└──────────────────────────────┘
Counter-example: if the Client carries the Builder through 3 layers,
the Builder becomes a hidden parameter -> bugs nobody can trace.05 — Edit freely, run it right here
Try it: three builds, two blocked at the gate
type Config = { min: number, max: number, step: number, value: number, label: string }
class Slider {
private constructor(private readonly c: Config) {}
static from(c: Config) { return new Slider(c) }
toString() {
return 'Slider(' + this.c.label + ' min=' + this.c.min + ' max=' + this.c.max
+ ' step=' + this.c.step + ' value=' + this.c.value + ')'
}
}
class SliderBuilder {
#min = 0
#max = 100
#step = 1
#value = 0
#label = 'slider'
min(v: number) { this.#min = v; return this }
max(v: number) { this.#max = v; return this }
step(v: number) { if (v <= 0) throw new Error('step must be greater than 0'); this.#step = v; return this }
value(v: number) { this.#value = v; return this }
label(s: string) { this.#label = s; return this }
build(): Slider {
if (this.#min >= this.#max) throw new Error('min must be less than max')
if (this.#value < this.#min || this.#value > this.#max)
throw new Error('value ' + this.#value + ' is outside [' + this.#min + ', ' + this.#max + ']')
if ((this.#max - this.#min) % this.#step !== 0)
throw new Error('step ' + this.#step + ' does not evenly divide the range ' + (this.#max - this.#min))
return Slider.from({ min: this.#min, max: this.#max, step: this.#step, value: this.#value, label: this.#label })
}
}
function attempt(tag: string, fn: () => Slider) {
try { console.log('OK ' + tag + ' -> ' + fn()) }
catch (e) { console.log('DENY ' + tag + ' -> ' + (e as Error).message) }
}
attempt('valid', () => new SliderBuilder().min(0).max(100).step(5).value(20).label('Volume').build())
attempt('value', () => new SliderBuilder().max(100).value(150).build())
attempt('step', () => new SliderBuilder().min(0).max(100).step(7).build())OK valid -> Slider(Volume min=0 max=100 step=5 value=20) DENY value -> value 150 is outside [0, 100] DENY step -> step 7 does not evenly divide the range 100
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- Many optional fields (roughly 4 or more) and cross-field constraints — meaning some combinations of values are forbidden.
- You want the Product to be immutable and every existing instance to be valid, so the rest of the code never has to re-check.
- Construction is spread across multiple steps or multiple places: middleware A sets the timeout, module B sets headers, and somewhere else finally sends.
- The order of operations is business logic: no
wherebeforefrom, no changes aftersend()(type-state). - You expose an API to another team and want them to have no way to create an invalid object — the builder becomes executable documentation instead of a wiki page.
- You need several variants from the same base configuration (clone, then change 2 fields): keep the builder alive deliberately, then call
build()multiple times.
Don't use it when
- Over-engineering is this pattern's default failure mode, and it's sneaky because builder code looks very skilled. A constructor with many parameters is NOT a reason by itself. With no cross-field invariants and no multi-stage construction,
build()is justreturn new X(...)in disguise: you've added 40 lines of mutable state, an extra allocation, and a layer of indirection between the reader and the truth. The 12-line options object wins. - Fluent APIs hide a classic trap: a setter returning
thismeans the object is silently mutated.const b = new Builder().min(0); const a = b.max(10); const c = b.max(20)—aandcare the same object, andajust got changed to 20. Either have setters clone and return a new copy (zod does this), or accept it and document it in big letters. - Don't let a Builder travel through multiple layers. A service that receives a builder and "conveniently" sets one more field is a hidden parameter: the function's behavior can no longer be read from its signature, and you'll spend two days debugging one
.set()in the wrong place. A builder should live and die within one function. - Locking the constructor with TypeScript's
privateis only compile-time safety:(Slider as any)or plain JS walks right around it. If you truly need the guarantee, don't export the class — export only the builder and the type, and close it off at the module boundary. - A fluent chain of 15
.withX()calls doesn't read better than an options object, it just reads differently; and the moment you have to break the chain with anif, fluent loses all its reason to exist. Validating input from users/HTTP still belongs at the boundary with a schema (zod/valibot) — Builder doesn't replace validation of untrusted data.
07 — You have met it already, just not by name
In real code
Typed query builders: Kysely, Drizzle, Prisma.sql
The most familiar example in the Node/TS world: db.selectFrom("user").where("id", "=", 1).limit(1).execute(). State accumulates step by step, and execute()/compile() is build() — only then is the SQL generated, and only then is it checked. Typed libraries also use generics so that not-yet-valid methods don't exist on the type, which is type-state in the full sense.
Commander / Cac: program.option(...).parse(process.argv)
A true CLI builder in Node: you add options, subcommands, descriptions, defaults — and parse() is the final gate, where arguments are coerced, defaults applied, and bad values rejected. The user never touches a half-finished config object.
Zod: schema.refine(...).transform(...).parse(input)
Fluent but immutable: every .refine()/.optional() returns a new schema instead of modifying the old one — exactly how to dodge the aliasing trap from the pitfalls. parse() is build(): every cross-field constraint (superRefine) is enforced once, in one place.
Counter-example: Prisma findMany and defineNuxtConfig
prisma.user.findMany({ where, orderBy, take }) and defineNuxtConfig({ ... }) are called in thousands of places every day, all using a flat options object with defaults, no builder anywhere. They're doing just fine. That's real-world proof that "many optional parameters" on its own is not a reason to build a builder.
08 — Try it yourself
Exercise
Write a `RetryPolicy` with 4 parameters: `attempts`, `baseMs`, `maxMs`, `jitter`. Constraints: `attempts >= 1`, `baseMs > 0`, `maxMs >= baseMs`, `jitter` within `[0, 1]`. Make three versions: (1) a constructor with 4 positional parameters, (2) options object + defaults + a `buildSlider`-style validator, (3) `RetryPolicy.builder().attempts(5).baseMs(100).build()`. Then **pick** one version and write down why in one sentence.
Hints, open them one at a time:
- Which constraints are cross-field? (
maxMs >= baseMs,jitterin range.) Which ones can a single field know on its own? - Single-field rules are checked in the setter so the error points at the wrong line. Cross-field rules are checked in
build()because only then do you have all the data. - How do your version 2 and version 3 differ, if
build()just calls a single validate function? Answering that honestly is the exercise.
All three versions pass the validation task. Version 1 is out immediately because new RetryPolicy(3, 200, 5000, 0.2) is unreadable. Most projects should pick version 2: one createRetryPolicy(opts) function with defaults + validation, no state, no extra allocation. Pick version 3 when the configuration is assembled in several places (lib A sets baseMs, app B sets attempts, CI sets maxMs) or when you want attempts() to fail right at the wrong line. Stating clearly which one you chose is half the exercise — someone who can't tell these two versions apart is someone who'll build a builder for everything.
type RetryOpts = { attempts?: number, baseMs?: number, maxMs?: number, jitter?: number }
class RetryPolicy {
private constructor(
readonly attempts: number,
readonly baseMs: number,
readonly maxMs: number,
readonly jitter: number,
) {}
static builder() { return new RetryPolicyBuilder() }
static create(opts: RetryOpts = {}): RetryPolicy {
const o = { attempts: 3, baseMs: 200, maxMs: 5000, jitter: 0.2, ...opts }
if (o.attempts < 1) throw new Error("attempts must be >= 1")
if (o.baseMs <= 0) throw new Error("baseMs must be > 0")
if (o.maxMs < o.baseMs) throw new Error("maxMs must be >= baseMs")
if (o.jitter < 0 || o.jitter > 1) throw new Error("jitter must be within [0, 1]")
return new RetryPolicy(o.attempts, o.baseMs, o.maxMs, o.jitter)
}
}
class RetryPolicyBuilder {
#o: RetryOpts = {}
attempts(n: number) { if (n < 1) throw new Error("attempts must be >= 1"); this.#o.attempts = n; return this }
baseMs(n: number) { if (n <= 0) throw new Error("baseMs must be > 0"); this.#o.baseMs = n; return this }
maxMs(n: number) { this.#o.maxMs = n; return this }
jitter(n: number) { this.#o.jitter = n; return this }
build() { return RetryPolicy.create(this.#o) } // cross-field rules live here
}
const p = RetryPolicy.builder().attempts(5).baseMs(100).maxMs(2000).jitter(0.1).build()
console.log("attempts=" + p.attempts + " baseMs=" + p.baseMs + " maxMs=" + p.maxMs)
console.log("default: " + JSON.stringify(RetryPolicy.create()))09 — Read them in pairs to see the essence
Related patterns
- Factory MethodSame creational family and they often nest: Factory Method answers "which kind to build", Builder answers "how to build it". Your builder should very often be called from a factory function.
- PrototypeA natural pair when you need many variants: instead of building from scratch, clone a base configuration, change a few fields, and build again.
- FacadeBoth hide complexity, but Facade hides it by **shrinking the API** (one call and you're done), while Builder hides it by **spreading** object construction over several steps.
- FlyweightOpposite goals: Builder produces many valid objects from different configurations, Flyweight shares one instance across users. Read this pair to know when to create more objects and when not to.