Every time Kancil Courier needs a new report on what's in the truck, the old code adds one method to every kind of shipment. The report may be the total shipping cost, labels or a parcel count. There are four kinds of shipment, so four classes have to change for one report.
The Visitor pattern does the opposite. One report (or any operation) over several kinds of object goes into one separate object, called a visitor, with one method per kind. The data being reported on isn't changed at all. Picture a few inspectors who check what's in a Kancil Courier truck before it leaves. One inspector from finance calculates the shipping costs, one from printing makes the labels, and one from loading counts the parcels. They check the same items, and each inspector carries their own checklist with one row per kind of item: document, parcel, cargo, sack. A new inspector only needs to bring a new checklist. But when a new kind of item goes on the truck, every checklist needs one more row. In code, each inspector is one visitor, each row on a checklist is one method for one kind, and the items on the truck are the data, which isn't changed.
The problem: every new report adds a method to every kind
Kancil Courier's truck carries documents, parcels, cargo, and sacks holding other shipments. If every report is written as a method on every kind, the classes keep growing:
class Parcel {
shippingCost() { /* ... */ }
label() { /* ... */ }
count() { /* ... */ }
// an insurance report, a tax report, ... every new report: edit Document, Parcel, Cargo, Sack
}
One report is spread over four classes, and the shipment kinds, which should be stable (rarely changing), change every month, every time a report is added.
Visitor: one report, one object
In the Visitor version, the truck's contents are plain data. truck itself is of the kind sack, because a truck is also a container of shipments. The accept function picks the visitor's method from the kind of each shipment, and shippingVisitor holds the cost rule for each kind:
const truck = {
type: "sack", code: "TRUCK-1", items: [
{ type: "document", trackingNo: "KCL-0011" },
{ type: "parcel", trackingNo: "KCL-0012", kg: 2 },
{ type: "cargo", trackingNo: "KCL-0013", kg: 4 },
{ type: "sack", code: "SACK-A", items: [
{ type: "document", trackingNo: "KCL-0014" },
{ type: "parcel", trackingNo: "KCL-0015", kg: 3 },
] },
],
}
function accept(item, visitor) {
switch (item.type) {
case "document": return visitor.visitDocument(item)
case "parcel": return visitor.visitParcel(item)
case "cargo": return visitor.visitCargo(item)
case "sack": return visitor.visitSack(item)
default: throw new Error("Unknown kind: " + item.type)
}
}
const shippingVisitor = {
visitDocument: () => 8,
visitParcel: (p) => p.kg * 10,
visitCargo: (k) => Math.max(k.kg, 10) * 6,
visitSack(sack) {
return sack.items.reduce((total, item) => total + accept(item, this), 0)
},
}
console.log(accept(truck, shippingVisitor)) // 126
How the 126 adds up:
| shipment | method called | cost |
|---|---|---|
| KCL-0011, document | visitDocument |
8 |
| KCL-0012, parcel 2 kg | visitParcel |
2 × 10 = 20 |
| KCL-0013, cargo 4 kg | visitCargo |
minimum 10 kg × 6 = 60 |
| SACK-A: document + parcel 3 kg | visitSack, then its contents |
8 + 30 = 38 |
| TRUCK-1 | visitSack |
126 |
accept(item, visitor)picks the visitor's method from the shipment's kind. That function is the only place that readsitem.type.shippingVisitorhas one method per kind. All the cost rules are in this object.visitSackcallsacceptagain for each item inside, passingthis(the same visitor), andreduceadds up the results. So a sack inside a sack gets counted too.visitSackis written as a regular method, not an arrow function, because an arrow function has nothisof its own.- A new report is only one new object. A
countVisitorwithvisitDocument: () => 1,visitParcel: () => 1,visitCargo: () => 1and avisitSackthat adds up its contents gives5, and thetruckdata isn't touched.
Double dispatch: two choices in one call
Which method runs depends on two things: the kind of shipment (parcel or cargo) and the report (cost or label). While the program runs, Java and JavaScript only pick a method from one object, the object before the dot. The class version of Visitor uses two calls so the kind and the report both have a part in the choice. That trick is called double dispatch (picking the method twice):
class Parcel {
constructor(trackingNo, kg) { this.trackingNo = trackingNo; this.kg = kg }
accept(visitor) { return visitor.visitParcel(this) } // choice 1: the kind is Parcel
}
new Parcel("KCL-0012", 2).accept(shippingVisitor) // choice 2: the visitor is shippingVisitor → 20
parcel.accept(visitor) picks the accept of the Parcel class. Then inside it, visitor.visitParcel(this) picks the method of the visitor that was passed in.
In JavaScript: a switch on type, or a map
Shipment data in JavaScript is usually plain objects from JSON, say { type: "parcel", kg: 2 } from an API. Objects from JSON have no accept method, so the accept(item, visitor) function with a switch on type above already makes the first choice. A lot of JavaScript code goes one step further: no visitor, but one function per report, with its own switch:
function shippingCost(item) {
switch (item.type) {
case "document": return 8
case "parcel": return item.kg * 10
case "cargo": return Math.max(item.kg, 10) * 6
case "sack": return item.items.reduce((total, x) => total + shippingCost(x), 0)
}
}
The benefit is the same: one report is in one place, and a new report doesn't change the data. Another form is a map, an object that pairs each kind with its function: const SHIPPING = { document: () => 8, parcel: (p) => p.kg * 10, ... }, then SHIPPING[item.type](item). In TypeScript, the most common form is a discriminated union (type Shipment = Document | Parcel | Cargo, told apart by the type field) with an exhaustive switch (complete: every kind must have a case). With one extra check in the default (the never type), the compiler reports an error for a kind that has no case yet. You get what Visitor gives, with far less code.
A new kind: the price Visitor pays
A new report is cheap. A new kind is expensive: every report has to learn it. This is what happens when { type: "electronics", trackingNo: "KCL-0016", kg: 1 } goes on the truck:
- The
shippingCostfunction with aswitchand nodefaultreturnsundefinedfor electronics, and126 + undefinedisNaN. The printed total isNaN, with no error. acceptwithdefault: throwstops right away withError: Unknown kind: electronics. That's better, because the mistake is visible.- Once
case "electronics"is added toaccept, a visitor that wasn't givenvisitElectronicsstops withTypeError: visitor.visitElectronics is not a function.
So Visitor fits when the kinds are stable and the reports keep growing. When the kinds of shipment are what keeps growing, putting the behaviour on each kind is easier.
Exercise: Evaluator and Printer
In the exercise, you use the same shape for a tree of maths expressions, a calculation kept as a tree. Each number and each operation is one node (a point in the tree). The nodes are { type: "num", value } for a number and { type: "bin", op, left, right } for an operation with two sides, left and right. op is "+" or "*". You write:
accept(node, visitor): callvisitor.visitNum(node)for"num",visitor.visitBin(node)for"bin", and return the result.createEvaluator(), the visitor that calculates:visitNum(n)returnsn.value,visitBin(n)calculatesaccept(n.left, this)andaccept(n.right, this), then adds them for"+"or multiplies them for"*".createPrinter(), the visitor that writes text:visitNum(n)returnsString(n.value),visitBin(n)returns"(" + left + " " + op + " " + right + ")", with left and right being the text fromaccept.
For the tree (1 + 2) * 3, the console prints 9, then ((1 + 2) * 3). The depth visitor (how many levels the tree has), already in the starter, gives 3 for that tree and 1 for a single number. The evaluator is also checked on another tree: 3 * 4 must give 12.
⚠️ Why is the report empty or NaN?
- A
switchwith nodefault. A new kind becomesundefined, thenNaN, with no error. Throw an error in thedefault, or have TypeScript check everycase(thenevertype in thedefault). - An arrow function that uses
this.visitBin: (n) => accept(n.left, this)doesn't get the visitor asthis. Use a regular method,visitBin(n) { ... }. - A missing
return. Anacceptthat callsvisitor.visitNum(node)withoutreturnmakes every resultundefined. - Spaces in the Printer. The result must be
((1 + 2) * 3): one space on each side of the operator, no spaces inside the brackets.
TL;DR: Visitor puts one report over several kinds of object in one separate object, called a visitor, with one method per kind (visitDocument, visitParcel, visitCargo, visitSack). The function accept(item, visitor) picks the method from the shipment's kind. A new report is one new visitor that doesn't touch the data: TRUCK-1's cost = 126, parcel count = 5. Double dispatch: the method that runs is picked from the kind of object and the kind of visitor at the same time. In JavaScript, JSON data is usually reported on with a switch on type or with a map (an object with one function per kind). In TypeScript, you use a discriminated union (several types told apart by the type field) and an exhaustive switch, which must have a case for every kind. The cost: a new kind must be added to every visitor, and a switch without a default quietly gives NaN for a forgotten kind. In the exercise, accept picks visitNum or visitBin. For the calculation tree (1 + 2) * 3, the Evaluator (the visitor that calculates) gives 9, and the Printer (the visitor that writes text) prints ((1 + 2) * 3).
⚡ One report, one object
Write:
const shippingVisitor = {
visitDocument: () => 8,
visitParcel: (p) => p.kg * 10,
visitCargo: (k) => Math.max(k.kg, 10) * 6,
visitSack(sack) {
return sack.items.reduce((total, item) => total + accept(item, this), 0)
},
}
console.log(accept(truck, shippingVisitor)) // 126
Meaning: Visitor puts one report over several kinds of object in one object, with one method per kind. Here truck holds a document, parcels, cargo and a sack of other shipments. truck itself is of the kind sack, because a truck is also a container of shipments. accept(item, visitor) picks the visitor's method from the shipment's kind, and visitSack calls accept again for each item in the sack. visitSack is a regular method, because an arrow function has no this of its own.
⚡ New reports are cheap, new kinds are expensive
Guess first: the function shippingCost calculates the cost of that truck's contents with one switch on the kind of shipment, with no default, and gets 126. Then an item of the kind electronics goes on the truck. What total gets printed?
NaN, with no error. Electronics becomes undefined, and 126 + undefined is NaN.
Meaning: Adding a new report (an operation) is easy and doesn't touch the data, but every new kind has to be taught to every visitor. So Visitor fits when the kinds are stable and the reports keep growing. To make a forgotten kind show right away, throw an error in the default.
⚡ In JavaScript: a switch or a map
Meaning: JSON data is plain objects with no accept method. Such data is usually reported on with a switch on type, or with a map (an object with one function per kind). In TypeScript, a discriminated union (several types told apart by the type field) with an exhaustive switch (complete, checked with the never type in the default) makes the compiler report an error for a kind that has no case yet.