Builder Pattern — Design Patterns

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…

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.

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

The builder: put together step by step

A builder becomes useful when one of these three things is true:

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

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 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

⚠️ Why does the build come out broken?

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.

What you will learn