The writer of this line wants the parcel in a wooden crate (a wooden box that protects the goods): new Shipment("KCL-0001", "cargo", 12, true, false, 150, 0, ["Glass inside"]). Does the parcel get the crate or not? From the line alone you can't tell. You have to open the constructor first.
The Builder pattern puts together an object with many optional parts step by step. The thing that puts it together is called a builder: an object with one method for each part, and each method is named after its part. At the end, build() checks the result and hands over the finished object. Picture a parcel form where every box has a label: insurance, wooden crate, COD (cash on delivery: the receiver pays when the parcel arrives), notes. You only fill in the boxes you need. Before the tracking sticker is printed, a clerk checks the form once. Compare that with a form of eight empty boxes and no labels, where you only know what a box means from where it sits. In code, the labelled form is the builder, each box you fill in is one method call, and the clerk's check is build(). The form with no labels is a constructor with eight arguments in a row.
The problem: eight arguments in a row
A Kancil Courier shipment has three required parts (tracking number, service, weight) and five optional ones. The Shipment class below takes all eight as arguments in a row:
class Shipment {
constructor(trackingNo, service, kg, insurance, woodenCrate, cod, itemValue, notes) {
Object.assign(this, { trackingNo, service, kg, insurance, woodenCrate, cod, itemValue, notes })
}
}
const s = new Shipment("KCL-0001", "cargo", 12, true, false, 150, 0, ["Glass inside"])
console.log(s.insurance, s.woodenCrate) // true false
The fourth argument is insurance, and the fifth is woodenCrate. The writer swapped true and false in those two places. So the parcel gets insurance and no crate. There is no error, because two swapped booleans are still booleans.
- What each argument means is only known from its position.
true, falsein the line that calls it doesn't say what either value means. - Optional parts you don't use still have to be filled with
falseor0, so that the arguments after them reach their place. - A ninth part placed between the existing arguments means changing every
new Shipment(...)call.
JavaScript's first step: one object of options
JavaScript has a built-in cure: pass one object of options, and take its contents out with destructuring (copying the values of an object into variables with the same names), defaults included.
function createShipment({ trackingNo, service = "regular", kg = 1, insurance = false, itemValue = 0, woodenCrate = false, cod = 0, notes = [] }) {
return { trackingNo, service, kg, insurance, itemValue, woodenCrate, cod, notes }
}
const s = createShipment({ trackingNo: "KCL-0001", service: "cargo", kg: 12, woodenCrate: true, cod: 150 })
console.log(s.insurance, s.woodenCrate) // false true
- Every value is named, so the order is free. A part you leave out takes its default (
= false,= 0). HerewoodenCrate: trueis easy to read, and the result is right: no insurance, with a crate. - When every part is known in one place, this is enough. Plenty of JavaScript code stops here, and that's fine.
The builder: put together step by step
A builder becomes useful when one of these three things is true:
- The object is filled in stages: the checkout page fills in the service and weight, the next step adds insurance, the last one COD.
- A part can be added many times, like the notes.
- A rule about the combination (a rule about several parts together) is checked once at the end.
The ShipmentBuilder class below puts a shipment together in this way:
class ShipmentBuilder {
constructor(trackingNo) {
this.data = { trackingNo, service: "regular", kg: 1, insurance: false, itemValue: 0, woodenCrate: false, cod: 0, notes: [] }
}
service(name) { this.data.service = name; return this }
kg(n) { this.data.kg = n; return this }
insurance(itemValue) { this.data.insurance = true; this.data.itemValue = itemValue; return this }
woodenCrate() { this.data.woodenCrate = true; return this }
cod(amount) { this.data.cod = amount; return this }
note(text) { this.data.notes.push(text); return this }
build() {
if (this.data.woodenCrate && this.data.service !== "cargo") {
throw new Error("Wooden crate is for cargo only")
}
return { ...this.data, notes: [...this.data.notes] }
}
}
const shipment = new ShipmentBuilder("KCL-0001")
.service("cargo")
.kg(12)
.woodenCrate()
.cod(150)
.note("Glass inside")
.note("Do not drop")
.build()
console.log(shipment.woodenCrate, shipment.insurance) // true false
console.log(shipment.notes.join(", ")) // Glass inside, Do not drop
- The
constructorsets the defaults. A part whose method is never called keeps its default. - Every method ends with
return this.thisis the builder itself, so.service("cargo")returns the same builder, and.kg(12)can be called right after it. Calls joined with dots like this are called method chaining. A set of methods made to be chained is called a fluent API: the call reads like a sentence. note()may be called many times. Each call adds one note to the array.build()is the only place the rules are checked. For example,new ShipmentBuilder("KCL-0002").service("express").woodenCrate().build()stops withError: Wooden crate is for cargo only. This error happens before a half-made shipment gets into the system.build()returns a copy ({ ...this.data }and a new array). So if the builder is changed afterwards, a shipment that's already made doesn't change.
So for an object with many optional parts, a builder gives you two things. The line that calls it reads clearly, because each part is named. And it keeps the checks gathered in one place: build().
A smaller example of the same idea: an add(x) method adds x to an array and then does return this. The call .add("a").add("b").add("c") fills that array with three letters. Then build() joins them with join("-") and gives a-b-c.
The Gang of Four builder. The builder above is the common form in JavaScript: many optional parts, chained with a fluent API. The builder in the Gang of Four book has another goal: to separate the building steps from the shape of the result. One Director runs the same steps, and different builders produce different results. For example, a shipping label made as text or as JSON:
function makeLabel(builder) { // Director: the order of the steps is always the same
builder.trackingNo("KCL-0001")
builder.destination("Riverside")
return builder.result()
}
class TextLabel {
constructor() { this.lines = [] }
trackingNo(t) { this.lines.push("Tracking: " + t) }
destination(d) { this.lines.push("To: " + d) }
result() { return this.lines.join(" | ") }
}
class JsonLabel {
constructor() { this.data = {} }
trackingNo(t) { this.data.trackingNo = t }
destination(d) { this.data.destination = d }
result() { return JSON.stringify(this.data) }
}
console.log(makeLabel(new TextLabel())) // Tracking: KCL-0001 | To: Riverside
console.log(makeLabel(new JsonLabel())) // {"trackingNo":"KCL-0001","destination":"Riverside"}
makeLabel is the Director: it always calls trackingNo(), destination(), then result(), without knowing the shape of the result. TextLabel puts together text, and JsonLabel puts together JSON. So a new format needs only one new builder class. Pick this version when one building process must produce several formats. Pick the fluent builder above when the problem is many optional parts.
The exercise: URLBuilder
In the exercise, you use the same shape for URLs. The starter (the code already in the editor) holds a URLBuilder class with empty methods protocol(p), host(h), path(p), query(k, v) and build():
- The default protocol is
"https", set in theconstructor. query(k, v)may be called many times. Keep each pair in an array, for examplethis._query.push([k, v]).build()puts togetherprotocol + "://" + host + path. After that come a"?"and thek=vpairs joined with"&". The question mark is written only when there is a query.
The expected results: https://api.example.com/users, https://example.com/search?q=laravel&page=2 and http://localhost/.
When you don't need a builder
- An object with two parts.
{ lat: -6.2, lng: 106.8 }is already clear.new PointBuilder().lat(-6.2).lng(106.8).build()adds a class and three calls for the same result. - Every part is known in one place. Use one object of options.
- No combination rules and no repeated parts. The builder is only extra code that gives you nothing.
⚠️ Why does the build come out broken?
- Forgetting
return this. That method returnsundefined. For example, ifcod()forgetsreturn this, the.note("Glass inside")call after it stops withTypeError: Cannot read properties of undefined (reading 'note'). - Forgetting
.build(). What you hold is still the builder, not the shipment.shipment.woodenCrateis then a method of the builder, andif (shipment.woodenCrate)is always true, becauseifalways treats a function as true. build()returningthis.datadirectly. The finished shipment still shares thenotesarray with the builder, so a note added to the builder afterwards also lands in that shipment. Return a copy.- A question mark that's always written. A URL with no query becomes
https://shop.com/cart?. Add the"?"only when the query array isn't empty.
TL;DR: When a constructor takes many arguments in a row, the arguments are easy to mix up, and no error tells you. In JavaScript the first fix is one object of options with defaults. A builder (an object that puts another object together) is for when the object is put together in stages, has repeated parts, or has rules checked at the end. The builder's constructor sets the defaults. Each method fills one part and then does return this so the calls can be chained (a fluent API: a chain of methods that reads like a sentence). build() checks everything in one place and returns a copy of its data. For a two-part object, an object literal (an object written directly with curly brackets) is enough.
⚡ Eight arguments in a row
Write:
const s = new Shipment("KCL-0001", "cargo", 12, true, false, 150, 0, ["Glass inside"])
console.log(s.insurance, s.woodenCrate)
Guess first: the Shipment constructor takes the tracking number, service, weight, insurance, woodenCrate, then three other parts, in that order. The writer of this line wants the parcel in a wooden crate (a wooden box that protects the goods). What gets printed?
true false. The fourth argument is insurance, the fifth woodenCrate, and the writer swapped the two. No error: two swapped booleans are still booleans.
Meaning: What each argument means is only known from its position. The first fix in JavaScript: pass one object of options with defaults, so every value is named.
⚡ Put together step by step
Write:
const shipment = new ShipmentBuilder("KCL-0001")
.service("cargo")
.kg(12)
.woodenCrate()
.cod(150)
.note("Glass inside")
.build()
Meaning: ShipmentBuilder is a builder (an object that puts another object together) for shipments. Each method fills one part of the shipment, for example .cod(150) for COD (cash on delivery: the receiver pays when the parcel arrives). Then the method does return this, which means it returns the same builder. So the next call can be added right after it, with a dot (a fluent API). Every part is named, so the call reads clearly. build() at the end hands over the finished shipment.
⚡ build() checks once
Meaning: build() is the only place the rules are checked. In ShipmentBuilder, a wooden crate on any service but cargo is refused with an error. build() returns a copy, so changing the builder afterwards doesn't change a shipment that's already made. A two-part object like { lat, lng } needs no builder.