Patterns & principles · 6 of 10 · 14 min read
The Builder pattern
Constructing something complicated one readable step at a time, and the two JavaScript features that make most builders unnecessary.
- Design patterns
Builder separates how an object is assembled from what it ends up being. The caller states the parts it cares about, in any order, and asks for the finished thing at the end.
The problem
// Six arguments, and the call site is unreadable:
function createRequest(url, method, headers, body, timeout, retries) { /* … */ }
createRequest('/api', 'POST', { 'X-Key': 'k' }, { a: 1 }, 5000, 3);
createRequest('/api', 'GET', null, null, null, 0); // what are those nulls?
Every optional parameter makes the next one worse, and the only way to set the sixth is to supply the five before it.
The fluent builder
Each step returns this, so the calls chain, and build() produces the finished object:
class RequestBuilder {
#config = { method: 'GET', headers: {}, timeout: 5000, retries: 0 };
url(value) { this.#config.url = value; return this; }
method(value) { this.#config.method = value; return this; }
header(name, value) { this.#config.headers[name] = value; return this; }
body(value) { this.#config.body = value; return this; }
timeout(ms) { this.#config.timeout = ms; return this; }
retries(n) { this.#config.retries = n; return this; }
build() {
if (!this.#config.url) throw new TypeError('url is required'); // validate once, here
return Object.freeze({ ...this.#config });
}
}
const request = new RequestBuilder()
.url('/api/orders')
.method('POST')
.header('Content-Type', 'application/json')
.body({ items: [] })
.retries(3)
.build();
console.log(request.method, request.retries, request.timeout); // POST 3 5000
Three things are doing the work: return this makes it chain, build() is the only place
that validates, and Object.freeze means the product cannot drift after it is built.
The one real advantage over an options object is that the builder can be passed around half-finished: a base configuration built in one module, specialised in another.
function authenticated(builder, token) {
return builder.header('Authorization', `Bearer ${token}`); // adds to whatever it was given
}
const base = new RequestBuilder().url('/api').timeout(10_000);
const call = authenticated(base, 'abc').method('DELETE').build();
console.log(call.headers.Authorization); // "Bearer abc"
The options object usually wins
JavaScript has named arguments in all but name, and defaults in the destructuring:
function createRequest({
url,
method = 'GET',
headers = {},
body = null,
timeout = 5000,
retries = 0,
} = {}) {
if (!url) throw new TypeError('url is required');
return Object.freeze({ url, method, headers, body, timeout, retries });
}
const request = createRequest({
url: '/api/orders',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
retries: 3,
});
console.log(request.method, request.timeout); // POST 5000
Same readability, same defaults, same single validation point — and about a fifth of the code.
| Fluent builder | Options object | |
|---|---|---|
| Lines of machinery | ~20 | 0 |
| Order-independent | yes | yes |
| Named parameters | yes | yes |
| Can be passed around partly built | yes | no, unless you spread it yourself |
| Steps that do something (compute, validate, fetch) | yes | no |
Repeatable steps (.where() twice) |
yes | needs an array |
| Discoverable by autocomplete | yes | with types, yes |
So: reach for the builder when a step is more than an assignment, when a step can repeat, or when the half-built thing is a value your code passes around. Otherwise write the options object.
Where it genuinely earns its place: repeatable steps
A query builder is the canonical case, because .where() is called many times and each call
contributes to a structure:
function query(table) {
const parts = { table, wheres: [], order: null, limit: null };
const api = {
where(field, op, value) { parts.wheres.push({ field, op, value }); return api; },
orderBy(field, dir = 'asc') { parts.order = { field, dir }; return api; },
limit(n) { parts.limit = n; return api; },
toSQL() {
let sql = `SELECT * FROM ${parts.table}`;
if (parts.wheres.length) {
sql += ' WHERE ' + parts.wheres.map((w) => `${w.field} ${w.op} ?`).join(' AND ');
}
if (parts.order) sql += ` ORDER BY ${parts.order.field} ${parts.order.dir}`;
if (parts.limit !== null) sql += ` LIMIT ${parts.limit}`;
return { sql, params: parts.wheres.map((w) => w.value) };
},
};
return api;
}
const { sql, params } = query('orders')
.where('status', '=', 'paid')
.where('total', '>', 100)
.orderBy('created_at', 'desc')
.limit(10)
.toSQL();
console.log(sql); // SELECT * FROM orders WHERE status = ? AND total > ? ORDER BY created_at desc LIMIT 10
console.log(params); // ["paid", 100]
Note it is a closure, not a class — no this to lose, and parts is genuinely private. Note
also that the values come back as parameters rather than interpolated into the string: a builder
that concatenates user input into SQL is how injection happens.
Immutable builders
The version above mutates itself, so two branches from the same base interfere:
const base = query('orders').where('status', '=', 'paid');
const a = base.where('total', '>', 100);
const b = base.where('total', '<', 10);
console.log(a.toSQL().params); // ["paid", 100, 10] — b leaked into a. They are the same object.
Returning a new builder each time fixes it, at the cost of an allocation per step:
function q(table, wheres = []) {
return {
where: (field, op, value) => q(table, [...wheres, { field, op, value }]), // a new builder
toSQL: () => ({
sql: `SELECT * FROM ${table}` + (wheres.length ? ' WHERE ' + wheres.map((w) => `${w.field} ${w.op} ?`).join(' AND ') : ''),
params: wheres.map((w) => w.value),
}),
};
}
const paid = q('orders').where('status', '=', 'paid');
console.log(paid.where('total', '>', 100).toSQL().params); // ["paid", 100]
console.log(paid.where('total', '<', 10).toSQL().params); // ["paid", 10] — independent
This is how real query builders behave, and it is worth saying in an interview: a chainable API that mutates is a shared-state bug waiting for someone to reuse a base.
Builders in the platform
const url = new URL('https://example.com');
url.searchParams.append('page', '2');
url.searchParams.append('tag', 'js');
url.searchParams.append('tag', 'node'); // a repeatable step
console.log(url.toString()); // https://example.com/?page=2&tag=js&tag=node
URL plus URLSearchParams is a builder: mutable steps, a repeatable one, and toString() as the
build(). So is document.createDocumentFragment() for a DOM subtree.
Common mistakes
Forgetting return this
Mistake. A step that sets a field and returns nothing.
Why it fails. The chain breaks at that call with Cannot read properties of undefined, and the
error names the next method, not the one that is wrong.
What to do instead. Return this (or the api object) from every step, and if the builder is a
closure, return the same api constant rather than rebuilding an object literal.
Letting build() hand out its internal state
Mistake. build() { return this.#config }.
Why it fails. The product and the builder share one object: another .timeout() call after
build() silently changes something you already shipped.
What to do instead. return Object.freeze({ ...this.#config }), and deep-copy anything nested.
Writing a builder for four optional fields
Mistake. Twenty lines of chaining to replace a destructured options object. Why it fails. It is more code, more indirection and worse for autocomplete, in exchange for nothing — every step is a plain assignment. What to do instead. The options object. Keep the builder for repeatable or computing steps.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What problem does the Builder pattern address?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.