Creational pattern
Builder
Assemble a complex object step by step through a fluent chain of calls, instead of stuffing every option into one giant constructor.
✗ The problem
Telescoping constructor / boolean soup
Every optional ingredient becomes another positional argument. The call site is a wall of unlabeled booleans — nobody can tell what they mean without opening the class.
class Burger {
constructor(size, cheese, bacon,
lettuce, egg, spicy, patties) { /* … */ }
}
// which true/false is which?? 🤯
new Burger('L', true, false, true, true, false, 2);
Unreadable call sites, easy to swap two args by accident, and every new
option means a new constructor overload.
✓ The pattern
↓ build()
A fluent builder assembles the product
Each add…() records one choice and returns this, so calls
chain. build() hands back the finished object at the end.
class BurgerBuilder {
constructor() { this.parts = []; }
addCheese() { this.parts.push('cheese'); return this; }
addBacon() { this.parts.push('bacon'); return this; }
build() { return new Burger(this.parts); }
}
new BurgerBuilder().addCheese().addBacon().build();
BurgerBuilder
add…() → returns this
Burger
finished product
✓ See it live
Pick toppings — watch the chain build itself
Click ingredients to call the matching add…(). Then call
build() to get the finished burger.
new BurgerBuilder()
0 toppings selected
✓ Takeaway
Step-by-step construction, readable call sites
- Builds a complex object incrementally — one clearly-named call per option.
- Readable call sites:
.addCheese().addBacon().build()beats seven positional booleans. - Great when there are many optional parameters; the product can even come out
immutable once
build()runs. - vs. Factory: a Factory picks which type to create; a Builder assembles the pieces of one complex object.
- Caution: overkill for objects with just 1–2 fields — a plain constructor is fine.
🎯 Principle applied: Builder gives object construction its own single responsibility, keeps call sites simple and readable (KISS), and avoids brittle telescoping constructors.
Back to all topics →