Pattern 22/22 · Behavioral
Visitor
Add new operations to a fixed tree of nodes without modifying any node: each node only declares "what kind I am", and all of the operation's logic lives in the visitor.
01 — It starts with code that is breaking
Problem
You're writing a calculator for a spreadsheet formula cell. The expression tree has three node types: Num, Neg, Add. Each node gets an evaluate() method. Clean, compact, tested in an afternoon.
Next week you need to print the formula back for the user. You open three classes and add toString(). Next month you need validation (undeclared variables, division by zero): open the three classes again. Next quarter you need to transpile to SQL: open the three classes again. Every new operation forces you to touch the entire set of frozen nodes, rerun tests for unrelated nodes, and re-review files whose diff changes nothing structural.
You try flipping it around: one file per operation, with a switch (node.kind) inside. Genuinely better — an operation's logic now lives in one readable place. But now the problem flips to the other axis: someone adds a Mul node, updates validate.ts and forgets export-sql.ts. If the nodes come from another package (a plugin system, an external file format), there's no closed union for the compiler to check for you, and the bug sits quietly until it hits production.
The deeper issue: the node tree is the stable part, operations are the part that keeps changing, yet the code keeps the two side by side. You want adding an operation = adding a file, not editing five files that were already stable. In other words, you want Open/Closed along the operation axis, and node-oriented code is closed along exactly that axis.
There's one more cost to "stuffing business logic into nodes": every node has to know every corner of the business — currency formatting, validation rules, how to generate SQL. The data structure turns into a dumping ground for business logic and can't be reused in another context: the same AST has to be walked differently by codegen, by a linter, by a formatter, by a version-migration tool.
02 — The idea, before touching code
Solution
Visitor flips who owns the operation: the operation doesn't live in the node, it lives in a separate object. Each node keeps exactly one method — accept(visitor) — and that method almost never changes: it calls back the visitor method matching the node's own type. The node answers "what kind am I", the visitor answers "what to do with that kind". These two dynamic choices are double dispatch, which TypeScript and JavaScript don't have built in.
The result: adding an operation costs just one new visitor, and the nodes don't change a single line. The price — which you must pay knowingly — is that adding a new node type forces you to edit the Visitor interface and every existing visitor. This is the Expression Problem: in TS/Java no structure is open in both directions for free. You pick the axis that changes more: fixed nodes + growing operations → Visitor. Growing nodes + fixed operations → a discriminated union with switch.
Saying the thing few people say: in JS/TS apps, most trees should use a union + switch with a never default, because it gives you compile-time exhaustiveness without a single line of ceremony. Visitor wins in three specific situations: operations contributed from outside (plugins, third-party packages), operations that need state while walking the tree, and when a tree is walked by many operations that you want to share one traversal. Outside those three, don't use Visitor just because it's a pattern with a name.
03 — Doing it for real, one code fragment per step
Step by step
A node tree with "business logic inside the nodes"
The first version of every tree looks the same: each node knows how to compute and render itself. The first operation is always fine. The second operation is when the bill arrives.
export class Num {
constructor(readonly value: number) {}
evaluate(): number { return this.value }
}
export class Neg {
constructor(readonly inner: Expr) {}
evaluate(): number { return -this.inner.evaluate() }
}
export class Add {
constructor(readonly left: Expr, readonly right: Expr) {}
evaluate(): number { return this.left.evaluate() + this.right.evaluate() }
}
export type Expr = Num | Neg | Add
new Add(new Num(2), new Neg(new Num(3))).evaluate() // -1toString() means reopening all three classes.evaluate() isn't wrong. What's wrong is when you need a second, a third method — and each addition means opening every node.The natural reaction: discriminated union + switch (and why it's strong)
Before learning Visitor, take a clear look at the alternative, because it wins most of the time. TypeScript describes the tree as a closed union, and a switch whose default assigns to never forces every switch to handle new node types — a missed case is a build error, not a runtime error.
So what's left for Visitor to sell? Three things, covered in step 8: operations from outside that aren't in your build, state while walking the tree, and shared traversal. Without those three, stopping at this step is the right call.
export type Expr =
| { kind: 'num', value: number }
| { kind: 'neg', inner: Expr }
| { kind: 'add', left: Expr, right: Expr }
function assertNever(x: never): never {
throw new Error('unhandled case: ' + JSON.stringify(x))
}
export function evaluate(e: Expr): number {
switch (e.kind) {
case 'num': return e.value
case 'neg': return -evaluate(e.inner)
case 'add': return evaluate(e.left) + evaluate(e.right)
default: return assertNever(e) // <- add a node type and forget this = BUILD ERROR
}
}never catches "forgot a case" when the node set is closed and you build all the source. Visitor exists for everything else.The Visitor contract: one method per node type
A Visitor is one operation, expressed as one method per node type. The generic parameter R is that operation's result type: evaluate returns number, print returns string, typeCheck returns a list of errors.
Why R matters: it lets a visitor return results upward instead of writing them into nodes. No mutable state hidden in the tree means the visitor is re-callable, testable, and can run in parallel.
import type { Add, Neg, Num } from './expr'
/** One operation = one interface, one method per node type. */
export interface Visitor<R> {
num(n: Num): R
neg(n: Neg): R
add(a: Add): R
}
/** The node contract: just one method, and it never changes. */
export interface Expr {
accept<R>(v: Visitor<R>): R
}Double dispatch: each node picks the method for its own type
Each node implements accept by calling back into the visitor with this as the argument. The node holds no business logic; it only declares its identity.
Two dispatches happen: first, OO polymorphism picks Num.accept rather than Add.accept; second, accept picks v.num rather than v.add. A visitor alone can't do the first (it doesn't know the node's type), a node alone can't do the second (it doesn't know the operation). Together they dispatch on the pair (node, operation).
import type { Expr, Visitor } from './visitor-contract'
export class Num implements Expr {
constructor(readonly value: number) {}
accept<R>(v: Visitor<R>): R { return v.num(this) }
}
export class Neg implements Expr {
constructor(readonly inner: Expr) {}
accept<R>(v: Visitor<R>): R { return v.neg(this) }
}
export class Add implements Expr {
constructor(readonly left: Expr, readonly right: Expr) {}
accept<R>(v: Visitor<R>): R { return v.add(this) }
}accept() is the only line a node has to write, and it will never change. The node loses all business knowledge.The first visitor: Evaluate
A visitor recurses by calling accept() again on child nodes. Subtrees are handled by the same mechanism that handled the parent — no manual loop, no switch, no instanceof.
import type { Visitor } from './visitor-contract'
export const evaluate: Visitor<number> = {
num: n => n.value,
neg: n => -n.inner.accept(evaluate),
add: a => a.left.accept(evaluate) + a.right.accept(evaluate),
}
// Client: doesn't need to know how many node types the tree has.
// new Add(new Num(2), new Neg(new Num(3))).accept(evaluate) // -1child.accept(thisVisitor). If traversal has its own logic (enter/leave, cutoff), it lives here — in one place, not scattered across nodes.The second visitor: adding an operation without touching the nodes
The second operation is the real test of the pattern. Write print: Visitor<string> — then look back at expr.ts and evaluate-visitor.ts: no file was modified. Users of your library can do the same, without forking.
In the logic-in-the-nodes version, adding an operation means opening N classes. With Visitor, it's one new file and one object. That's Open/Closed along the operation axis.
import type { Visitor } from './visitor-contract'
export const print: Visitor<string> = {
num: n => String(n.value),
neg: n => '-' + n.inner.accept(print),
add: a => '(' + a.left.accept(print) + ' + ' + a.right.accept(print) + ')',
}
// git status:
// new file: print-visitor.ts
// (no other changes)
//
// new Add(new Num(2), new Neg(new Num(3))).accept(print) // "(2 + -3)"The other side of the trade-off: adding a node type
Now add a Mul node. You must edit the Visitor interface (add mul(m: Mul): R) and edit every existing visitor, no exceptions. With generic R, the compiler will list every place you need to fix — that's the decent part of this design, but it won't do the work for you.
There's an escape hatch: add a fallback method unknown(node: Expr): R to the contract. Its price is that you lose exactly what you paid for — exhaustiveness silently turns into a fallback that runs at runtime. Only open it when nodes genuinely come from plugins.
// 1) The new node
export class Mul implements Expr {
constructor(readonly left: Expr, readonly right: Expr) {}
accept<R>(v: Visitor<R>): R { return v.mul(this) } // <- Visitor needs a new mul method (see step 3)
}
// 2) The Visitor contract has to open up:
// export interface Visitor<R> { num; neg; add; mul(m: Mul): R }
// 3) EVERY visitor needs the new method — the compiler raises this alarm for you:
// evaluate: { ..., mul: m => m.left.accept(evaluate) * m.right.accept(evaluate) }
// print: { ..., mul: m => '(' + ... + ' * ' + ... + ')' }
// typeCheck:{ ..., mul: m => ... }When not to use Visitor: union + switch, and the 3 conditions where Visitor wins
This version does almost everything Visitor does with fewer concepts, fewer files, and exhaustiveness still enforced by the compiler:
type Expr =
| { kind: 'num', value: number }
| { kind: 'neg', inner: Expr }
| { kind: 'mul', left: Expr, right: Expr }
const evalExpr = (e: Expr): number => {
switch (e.kind) {
case 'num': return e.value
case 'neg': return -evalExpr(e.inner)
case 'mul': return evalExpr(e.left) * evalExpr(e.right)
default: return assertNever(e)
}
}
// An "operation" over the tree as a plain function still gets passed around without accept():
const printExpr = (e: Expr): string => e.kind === 'num' ? String(e.value)
: e.kind === 'neg' ? '-' + printExpr(e.inner)
: '(' + printExpr(e.left) + ' * ' + printExpr(e.right) + ')'04 — Who talks to whom
Structure
- VisitorOne operation, declared as one method per node type. Generic `R` is the operation's result type.
- ConcreteVisitor`evaluate`, `print`, `typeCheck`. Holds its own state (if needed), never touches the nodes.
- Element (Expr)Declares `accept(visitor)`. This is the single extension point for operations.
- ConcreteElement`Num`, `Neg`, `Add`. Holds **structure** + one dispatch line. No business logic.
- ObjectStructureThe node tree (root and children), usually a Composite. The visitor walks it via recursive `accept`.
Client ── tree.accept(evaluate) ──► node (Num | Neg | Add)
│
│ accept(v): "what kind am I"
│ → calls v.<kind>(this)
▼
┌────────────────────────────────┐
│ Visitor<R> │
│ num(n): R │
│ neg(n): R │
│ add(a): R │
└────────────────────────────────┘
dispatch #1: node knows its own type (OO polymorphism)
dispatch #2: visitor picks behavior (operation lives OUTSIDE node)
────────────────────────────────────────────────────────────
Add an OPERATION → add 1 visitor file nodes unchanged
Add a NODE TYPE → edit Visitor + EVERY visitor (Expression Problem)05 — Edit freely, run it right here
Try it: three visitors on the same tree, nodes unchanged
interface Visitor<R> {
num(n: Num): R
neg(n: Neg): R
add(a: Add): R
}
interface Expr { accept<R>(v: Visitor<R>): R }
class Num implements Expr {
constructor(readonly value: number) {}
accept<R>(v: Visitor<R>): R { return v.num(this) }
}
class Neg implements Expr {
constructor(readonly inner: Expr) {}
accept<R>(v: Visitor<R>): R { return v.neg(this) }
}
class Add implements Expr {
constructor(readonly left: Expr, readonly right: Expr) {}
accept<R>(v: Visitor<R>): R { return v.add(this) }
}
// Operation 1
const evaluate: Visitor<number> = {
num: n => n.value,
neg: n => -n.inner.accept(evaluate),
add: a => a.left.accept(evaluate) + a.right.accept(evaluate),
}
// Operation 2
const print: Visitor<string> = {
num: n => String(n.value),
neg: n => '-' + n.inner.accept(print),
add: a => '(' + a.left.accept(print) + ' + ' + a.right.accept(print) + ')',
}
// Operation 3: added here, the three node classes above don't change a single line.
const size: Visitor<number> = {
num: () => 1,
neg: n => 1 + n.inner.accept(size),
add: a => 1 + a.left.accept(size) + a.right.accept(size),
}
const tree = new Add(new Num(2), new Neg(new Num(3)))
console.log('formula: ' + tree.accept(print))
console.log('value: ' + tree.accept(evaluate))
console.log('node count: ' + tree.accept(size))formula: (2 + -3) value: -1 node count: 4
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- The tree structure is relatively closed (a language's AST, a form schema, a versioned file format) but the number of operations keeps growing: lint, format, transpile, type-check, optimize, decompile.
- Operations contributed from outside your codebase: ESLint/Babel/PostCSS plugins, another team's package. They can't edit the switch in your source — but they can write a visitor.
- Operations that need state while walking the tree: a scope stack, a breadcrumb path, an accumulator, an error collection. A visitor is an object, so it holds state cleanly; a pure function doesn't.
- A heterogeneous tree (Composite) where you want one shared traversal engine instead of every operation writing its own recursion — conditional traversal (pruning branches, priority order) stays in one place.
- Different operations return different types (
number,string,Diagnostic[]) and you want each operation to control its own return type — genericRdoes exactly that. - You need to run several operations over the same tree in a single pass (a visitor pipeline) — you pay the traversal cost only once.
Don't use it when
- The Expression Problem. A new node type = editing the Visitor interface + every visitor. If your tree gains node types often (form schemas, protocol payloads), Visitor is a weekly tax. Switch/union is the winner there.
- Visitor breaks node encapsulation: to do its job, it needs access to child nodes, fields, metadata. The result is nodes forced to make everything public — or you add a separate
children()API, and now it's ceremony on top of ceremony. - It looks like a "professional" pattern, but it's one of the GoF patterns least needed at the app layer. Three node types, two operations, one repo: union +
switch+neveris shorter, easier to debug, and no file is called "visitor". - Don't collect results by mutating nodes (
node.result = ...) or module-level mutable state. Use the return value (R) or a context object passed down — otherwise the visitor isn't reentrant and your tests depend on run order. - Every visitor writes its own recursion, so traversal logic gets duplicated across visitors. As soon as traversal has real conditions (pruning subtrees, special ordering), extract a traversal engine and let visitors just receive nodes.
- Generic
Rwith one type per visitor makes combining several operations in one pass awkward. Design for it separately (a list of visitors, a shared context) if that's what you need — don't cram three operations into one visitor "for convenience".
07 — You have met it already, just not by name
In real code
Babel plugins
A Babel plugin is a visitor object: module.exports = () => ({ visitor: { CallExpression(path) { ...}, Identifier(path) { ...} } }). Babel owns the traversal, you declare behavior per node type. Adding a new transform never touches the @babel/types package.
ESLint rules
A rule exports create(context), which returns a map of methods keyed by ESTree node type: Literal(node) {...}, "Program:exit"(node) {...}. ESLint walks the tree once and calls the right method — a pure visitor, and the reason thousands of external rules exist without ESLint core knowing anything about them.
estree-walker (Svelte, Vite plugins)
walk(ast, { enter(node), leave(node) }) separates traversal from behavior: enter/leave are just two visitor methods, applied to every node type. This "generic visitor" is why the Svelte compiler can add transforms without modifying the walker.
PostCSS plugins
A PostCSS plugin declares visitors per CSS node type (Declaration, AtRule, Rule, Once, OnceExit) and PostCSS handles walking the tree. A plugin that renames custom properties is just an object with one method — no forking PostCSS.
TypeScript compiler API
ts.forEachChild(node, visit) / ts.visitNode go the other way: they don't package operations as objects, they just give you a tree-walking function and you decide everything in the callback. A reminder that traversal and visitor are two independent decisions.
08 — Try it yourself
Exercise
Given a form schema tree `Field | Group | Repeat`, write two operations, `validate(node): string[]` and `toText(node): string`, using Visitor. Then add a `toJSONSchema` operation **without modifying the nodes**, then add a `Divider` node type and list exactly which files have to change.
Hints, open them one at a time:
- Start from the contract:
interface Visitor<R> { field(f): R; group(g): R; repeat(r): R }. PickRper operation —string[]for validate,stringfor toText. - Nodes hold
children(orinner) and callchild.accept(v)to recurse. Don't useinstanceofinside a visitor — that's a sign you're drifting back toswitch. - For
Divider, count it all: 1 node file + 1 Visitor interface + one method in each visitor. That number is the lesson.
Three methods in the interface, three nodes implementing accept, and each operation is an object matching Visitor<R> that recurses via accept. Adding toJSONSchema = one new file. Adding Divider = editing the Visitor interface plus adding a method to each existing visitor — exactly the expensive direction of the Expression Problem.
interface Visitor<R> {
field(f: Field): R
group(g: Group): R
repeat(r: Repeat): R
divider(d: Divider): R
}
type SchemaNode = Field | Group | Repeat | Divider
class Field {
constructor(readonly name: string, readonly required = false) {}
accept<R>(v: Visitor<R>): R { return v.field(this) }
}
class Group {
constructor(readonly title: string, readonly children: SchemaNode[]) {}
accept<R>(v: Visitor<R>): R { return v.group(this) }
}
class Repeat {
constructor(readonly of: SchemaNode) {}
accept<R>(v: Visitor<R>): R { return v.repeat(this) }
}
class Divider {
accept<R>(v: Visitor<R>): R { return v.divider(this) }
}
// Operation 1: find required fields inside
const missingRequired: Visitor<string[]> = {
field: f => (f.required ? [] : [f.name]),
group: g => g.children.flatMap(c => c.accept(missingRequired)),
repeat: r => r.of.accept(missingRequired),
divider: () => [],
}
// Operation 2: print the tree as text
const toText: Visitor<string> = {
field: f => 'field ' + f.name,
group: g => g.title + ' { ' + g.children.map(c => c.accept(toText)).join('; ') + ' }',
repeat: r => 'repeat(' + r.of.accept(toText) + ')',
divider: () => '---',
}
// Operation 3: does NOT touch the nodes, nor the 2 visitors above
const labelCount: Visitor<number> = {
field: () => 1,
group: g => g.children.reduce((n, c) => n + c.accept(labelCount), 0),
repeat: r => r.of.accept(labelCount),
divider: () => 0,
}
const form = new Group('checkout', [new Divider(), new Field('email', true), new Repeat(new Field('line'))])
console.log('missing required: ' + JSON.stringify(form.accept(missingRequired)))
console.log(form.accept(toText))
console.log('label count: ' + form.accept(labelCount))09 — Read them in pairs to see the essence
Related patterns
- CompositeVisitor almost always comes with Composite: a tree of nodes that share a contract but differ in behavior, and Visitor is how you "add behavior from outside" to that tree without the Composite holding business logic.
- IteratorBoth separate "walking the structure" from "doing something". Iterator hands elements to the client one at a time (the client drives); Visitor takes an operation object and walks everything itself (the structure drives).
- StrategyVisitor is a Strategy for **the whole tree** instead of a single node: an operation object chosen at runtime. The difference is that Visitor needs double dispatch to pick the right method per node type.
- Template MethodTemplate Method keeps traversal in a base class and opens up one step; Visitor pushes the **entire** operation out of the tree. Want to change the traversal: Template Method; want to add operations: Visitor.