Visitor moves an operation out of a class hierarchy and into an object of its own. The elements of a structure (shapes, syntax-tree nodes, files) get a single method, accept(visitor), and every operation (area, SVG export, type checking) becomes a visitor class with one method per element type. New operations are then new classes, and the element classes never change. The price is the mirror image: a new element type forces a change to every visitor. The trick that makes it work, double dispatch, is worth understanding on its own.
Think of it like
Inspectors touring a building
A building is made of rooms: kitchens, bathrooms, bedrooms. An electrical inspector and a fire inspector both tour it, and each has a checklist page per kind of room. At every door the room only says "I am a kitchen, come in", and the inspector opens the kitchen page of their checklist. A new kind of inspection (plumbing) needs one new inspector with their own pages; the rooms do not change at all. A new kind of room (a sauna) is the hard case: every inspector's checklist needs a new sauna page before the next tour.
The problem
A drawing program holds shapes, Circle and Rect, and needs operations over them: the total area, an export to SVG, and next month a perimeter, a bounding box, a JSON format. The obvious design puts each operation on the shape interface and writes it in every shape class. This is the Before version in the visualizer above.
interface Shape {
area(): number;
toSvg(): string;
// perimeter(), toJson(), bounds()... all land here
}
class Circle implements Shape {
constructor(readonly r: number) {}
area() { return Math.PI * this.r ** 2; }
toSvg() { return "<circle r='" + this.r + "'/>"; }
}
class Rect implements Shape {
constructor(readonly w: number, readonly h: number) {}
area() { return this.w * this.h; }
toSvg() {
return "<rect width='" + this.w + "' height='" + this.h + "'/>";
}
}- Every new operation opens every shape class. Adding
perimeter()editsShape,CircleandRect. With ten shape classes it is eleven edits, and each one can break a class that has nothing to do with perimeters. - Unrelated concerns pile up in the model.
Circleknows geometry, SVG syntax, JSON field names and printing. A change to the SVG exporter is a change to the shape classes. - One operation is scattered. To review "the SVG export" you open every shape file, because each holds one piece of it.
- Sometimes the classes cannot be edited at all: they come from a library, or a parser generator writes them.
The pattern
Intent: represent an operation on the elements of an object structure as a separate object, so that new operations can be added without changing the classes of the elements. Each element knows only how to accept a visitor; the visitor holds the code for every element type. Methods on every class (plain polymorphism) remain the right design when operations are few and stable; Visitor is for the opposite situation, where the kinds of elements are stable and the operations keep coming.
- Visitor (
Visitor) - The interface of an operation: one method per concrete element class,
visitCircle(c)andvisitRect(r). It names every element type, which is why a new element type changes it. - Concrete visitor (
AreaVisitor,SvgVisitor) - One operation, written once for every element type. It can return a value or keep state across the elements it visits.
- Element (
Shape) - Declares
accept(v). That is the only method the operations need from it. - Concrete element (
Circle,Rect) - Implements
acceptwith one line: call the visit method for its own class and pass itself,v.visitCircle(this). - Object structure
- The collection being visited: here a list of shapes, often a tree built with Composite. It offers a way to apply a visitor to every element.
Double dispatch, step by step
Java, C++, C#, TypeScript and Python all use single dispatch: in x.m(y), the code that runs depends on the runtime class of x only. But the code for "area of a circle" depends on two runtime classes, the operation's and the shape's. Visitor gets that with two single-dispatch calls in a row, each one deciding half of the question:
client: s.accept(area) s is typed Shape; its runtime class
decides: Circle.accept runs
Circle: v.visitCircle(this) the method name is fixed (this is a
Circle); v's runtime class decides:
AreaVisitor.visitCircle runss.accept(v) runs... | v is an AreaVisitor | v is an SvgVisitor |
|---|---|---|
s is a Circle | AreaVisitor.visitCircle | SvgVisitor.visitCircle |
s is a Rect | AreaVisitor.visitRect | SvgVisitor.visitRect |
Why not just overload visit()?
class AreaVisitor {
double visit(Circle c) { return Math.PI * c.r() * c.r(); }
double visit(Rect r) { return r.w() * r.h(); }
}
Shape s = new Circle(1);
new AreaVisitor().visit(s); // does not compile: no visit(Shape)
// Inside Circle.accept, the static type of this IS Circle,
// so v.visit(this) picks visit(Circle) at compile time.
// accept turns the runtime type into a static type.It is tempting to skip accept, write overloads visit(Circle) and visit(Rect) and call area.visit(s). In Java and C++ that does not work, because overloads are chosen at compile time from the static types of the arguments; only the receiver is dispatched at run time. That is the job of accept: by the time the element calls back, the compiler knows its exact class. With overloads the callback is v.visit(this) (the C++ implementation below does that); with distinct names it is v.visitCircle(this), which is the only option in TypeScript and Python (no run-time overloading) and many Java codebases prefer anyway for readability. Languages with multiple dispatch (Common Lisp's CLOS, Julia) choose a method from the runtime types of all arguments, so they need no Visitor for this; Clojure's multimethods can dispatch on any function of the arguments, their types included. C# can opt in per call with dynamic, which resolves overloads at run time.
What the visualizer shows
- The class diagram is two hierarchies.
ShapewithCircleandRecton top,VisitorwithAreaVisitorandSvgVisitorbelow.Visitorlists one method per shape class: that list is the coupling the change requests will expose. - The ping-pong in the Sequence view. For each shape, a call goes from the client into the shape (
accept(area)) and immediately a second call goes from the shape out to the visitor (visitCircle(circle)), with the shape itself as the argument. The answer then travels back the same way: visitor to shape, shape to client. - The captions name both decisions. On the first call: "this object is a
Circle, soCircle.acceptruns". On the second: "this object is anAreaVisitor, soAreaVisitor.visitCircleruns". In the class diagram the first lightsCircleand itsimplementsedge, the second lightsAreaVisitor, its edge and the declaring interfaceVisitor. - Same call, different code. The second visitor makes
Circle.acceptsend exactly the samevisitCirclemessage, but now tosvg, soSvgVisitor.visitCircleruns. - Two change requests. The toolbar picker chooses which one the change button applies: New operation (add a perimeter) or New shape (add a right triangle). The side panel counts the classes each version had to touch.
Walkthrough
- 1
Build the structure
With With Visitor selected, the client creates
circle(radius 1) andrect(2 × 3) and puts them in a list typedShape[]. The shapes hold data and one method,accept. - 2
Create an operation
areais anAreaVisitor. It has no fields: it is the area formula for every kind of shape, one method per shape class. - 3
Dispatch 1, on the shape
The loop only knows
sas aShape, so it callss.accept(area). The runtime class ofsisCircle, soCircle.acceptruns. - 4
Dispatch 2, on the visitor
Circle.acceptknowsthisis aCircle, so it callsv.visitCircle(this). The runtime class ofvisAreaVisitor, soAreaVisitor.visitCircleruns and returns π.accepthands that value back to the client unchanged. - 5
Next shape
rect.accept(area)runsRect.accept, which callsvisitRect, andAreaVisitor.visitRectreturns 6. The total is π + 6, about 9.14. - 6
A second operation over the same shapes
The client creates
svg, anSvgVisitor, and loops again.Circle.acceptsends the samevisitCirclemessage, but to a different visitor, so different code runs. The output is<circle r='1'/><rect width='2' height='3'/>. - 7
Change request: a new operation
With New operation picked, press Add perimeter. The Visitor version adds one class,
PerimeterVisitor, and the run applies it like the others (2π + 10, about 16.28). No shape class and not evenVisitorchanged. The Before version had to editShape,CircleandRect. - 8
Change request: a new shape
Pick New shape and press Add triangles. Now the Before version wins: it adds
Triangleand edits nothing. The Visitor version addsTriangleand editsVisitor,AreaVisitorandSvgVisitor, because each must learnvisitTriangle.
Before and after
Operations as methods on the shapes
- One virtual call per operation, no extra classes
- Each new operation edits the interface and every shape class
- Each new shape is one new class, and the compiler lists the methods it must write
- Model classes collect unrelated code (geometry, SVG, JSON)
With Visitor
- Each operation lives in one class and can keep its own state
- A new operation is one new class; no element changes
- A new element type edits
Visitorand every visitor class - Two calls per element, and elements must expose what visitors need
| Change request | Measure | Without the pattern | With Visitor |
|---|---|---|---|
| Add perimeter (new operation) | Classes edited | 3 (Shape, Circle, Rect) | 0 |
| New classes | 0 | 1 (PerimeterVisitor) | |
| Lines changed | 7 | 0 | |
| Add triangles (new shape) | Classes edited | 0 | 3 (Visitor, AreaVisitor, SvgVisitor) |
| New classes | 1 (Triangle) | 1 (Triangle) | |
| Lines changed | 0 | 9 |
The two tables are one trade-off, which Philip Wadler named the expression problem in 1998: picture the code as a grid with element types as rows and operations as columns. Class-per-type designs make adding a row cheap and a column expensive. Visitor flips that: adding a column (an operation) is cheap, adding a row (a type) is expensive. Techniques that make both cheap exist (object algebras, type classes, open multimethods), but none of the everyday designs in Java, C++ or TypeScript does.
| Design | Add an operation | Add an element type |
|---|---|---|
| Methods on each class (plain polymorphism) | Edit every class | Add one class |
| Visitor | Add one visitor class | Edit Visitor and every visitor |
| Closed union plus pattern matching | Add one function | Edit every function (the compiler lists them) |
Variations
Results and traversal
The visualizer's visitors return a value through accept (a generic Visitor<R> and accept<R>(v: Visitor<R>): R), so the client combines the results. The Gang of Four version returns nothing: the visitor keeps a running result in a field (total += ...) and the client reads it afterwards. Returning is clearer for expression-like results (evaluate, print, type check) and keeps visitors stateless and reusable. Accumulating suits whole-structure results (counts, a collected list, a symbol table) and is the usual choice in C++, where a virtual function cannot be a template, so a generic accept is not available; the C++ implementation below accumulates. The other design choice is who walks the structure:
| Traversal lives in | How | Trade-off |
|---|---|---|
| The elements | A composite's accept calls v.visitFolder(this) and then child.accept(v) for each child | Written once and every visitor gets it, but every visitor gets the same order |
| The visitor | visitFolder loops over the folder's children and calls child.accept(this) | Each visitor chooses the order or prunes subtrees, at the cost of repeating the loop in every visitor |
| A separate walker | An Iterator or a library function walks the structure and calls the visitor at each node | Traversal and operation are fully separate; the walker can offer hooks such as before and after children |
Acyclic Visitor
In classic Visitor the dependencies form a cycle: Shape mentions Visitor (in accept), and Visitor mentions every concrete shape. Robert C. Martin's Acyclic Visitor breaks it: the visitor base is an empty interface, each element type gets its own small interface (CircleVisitor with visit(Circle)), and Circle.accept casts the visitor to CircleVisitor at run time (dynamic_cast in C++, instanceof in Java), skipping visitors that do not implement it. Adding a Triangle then touches no existing visitor, and modules compile independently. The costs are a cast on every visit and no compiler check that a visitor handles every type, so it suits large, layered systems rather than a small hierarchy.
The modern alternative: pattern matching over sealed types
Visitor exists largely because classic object-oriented languages could not switch on a type safely. Many now can: declare a closed set of types and match on them, and the compiler reports any type a match forgets. This has the same trade-off as Visitor (operations cheap, new types expensive) with far less code: no accept, no visitor interface, an operation is just a function. It can also match nested structure in one case (an addition whose left operand is the number zero), which Visitor cannot do neatly. The second implementation below writes the visualizer's operations this way in all four languages.
| Language | Closed types and matching | A forgotten type |
|---|---|---|
| Java 21 | A sealed interface with records; switch with record patterns such as case Circle(int r) | Compile error: the switch is not exhaustive |
| Kotlin | A sealed interface or sealed class; when (s) { is Circle -> ... } | Compile error |
| Rust | An enum with data in each variant; match | Compile error: non-exhaustive patterns |
| TypeScript | A union discriminated by kind; switch (s.kind) with assertNever(s) in default | Type error at assertNever |
| C++17 | std::variant<Circle, Rect>; std::visit with one lambda per type | Compile error, unless a generic auto lambda catches every type |
| Python 3.10+ | A union of dataclasses; match s: with case Circle(r): | Not checked at run time; mypy or pyright report it at assert_never |
In real code
| Where | What it is | Visitor idea |
|---|---|---|
Java annotation processing: ElementVisitor<R, P> in package javax.lang.model.element | Program elements (classes, methods, fields, packages) have accept(v, p); the visitor has one visit method per kind of element, plus visitUnknown. Methods have been added in later Java releases | Classic double dispatch with a generic result R and an extra argument P. New language constructs (modules in Java 9, record components in Java 16) brought new visit methods; the JDK's base classes such as SimpleElementVisitor14 supply defaults, so existing visitors cope: the cost of a new element type, absorbed by defaults |
Java FileVisitor<T> with Files.walkFileTree | Four callbacks (directory entered, file found, file failed, directory left), each returning a FileVisitResult such as CONTINUE or SKIP_SUBTREE; SimpleFileVisitor supplies defaults | A visitor without accept: the walker does the traversal and picks the method by event, and the visitor steers the walk |
Python ast.NodeVisitor and NodeTransformer | visit(node) calls visit_ plus the node's class name (visit_BinOp) or falls back to generic_visit, which visits the children; a transformer's return value replaces the node | Dispatch by name lookup instead of accept. A misspelled method (visit_Binop) is silently never called |
| Babel plugins and ESLint rules | An object whose keys are syntax-tree node types (Identifier, CallExpression); the traverser calls the matching function when it enters, and if asked leaves, each node | Many independent operations over one fixed tree format; ESLint runs the listeners of all enabled rules in a single traversal |
com.sun.source.tree.TreeVisitor and Clang's RecursiveASTVisitor are further examples, each with many visitors (checks, analyses, code generation) over one stable tree.When to use it, and when not to
Reach for Visitor when
- The element classes are stable but new operations keep arriving (syntax trees, document models, file trees)
- Operations are unrelated to the elements' main job (export, reports, validation) and each should live in one place
- The compiler should check that every operation handles every element type
- Your language has no exhaustive pattern matching over a closed set of types, or the hierarchy is a published API whose users add operations
Skip it when
- New element types are added often: each one edits every visitor
- There are one or two operations: a method on each class is simpler
- You own a closed set of types in Java 21, Kotlin, Rust, Scala, TypeScript or C++17: pattern matching gives the same checks with less code
- Operations need the elements' private state, so visitors would force you to expose it
Visitor vs similar patterns
| Pattern | How it differs | Example |
|---|---|---|
| Iterator | Iterator walks a collection and hands back elements; Visitor acts on each element with code chosen by its type. Iterator walks, Visitor acts, and they combine | for (s of shapes) s.accept(area) |
| Composite | Composite builds the tree (leaves and containers behind one interface); Visitor adds operations to that tree from outside instead of adding methods to every node class | Folder.size() on the nodes vs a SizeVisitor |
| Interpreter | Interpreter puts interpret() in each grammar class (easy to add node types). When a syntax tree needs many operations (evaluate, print, type check, optimize), they are often moved out into visitors | expr.interpret(ctx) vs expr.accept(new Printer()) |
| Strategy | A strategy is one algorithm behind one method, swapped into a context. A visitor is a family of methods, one per element type, selected by double dispatch | PaymentStrategy.pay() vs visitCircle / visitRect |
| Command | A command turns one request into an object to queue, log or undo. A visitor is also an operation as an object, but it is applied across a structure of different element types | new DeleteText(doc).execute() vs drawing.accept(new SvgVisitor()) |
Implementation
Circle and Rect accept a generic visitor; AreaVisitor and SvgVisitor return values through accept, and PerimeterVisitor is the change request added without touching the shapes. TypeScript, Java and Python use distinct method names (visitCircle, visitRect). The C++ version uses overloaded visit methods, which works because inside accept the type of *this is exact, and its visitors accumulate results in fields because a virtual function cannot be a template.
"""Visitor: each operation over the shapes is a class of its own."""
from __future__ import annotations
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Generic, TypeVar
R = TypeVar("R")
class Visitor(ABC, Generic[R]):
@abstractmethod
def visit_circle(self, c: Circle) -> R: ...
@abstractmethod
def visit_rect(self, r: Rect) -> R: ...
class Shape(ABC):
@abstractmethod
def accept(self, v: Visitor[R]) -> R: ...
@dataclass(frozen=True)
class Circle(Shape):
r: int
def accept(self, v: Visitor[R]) -> R:
# Dispatch 2: here self is a Circle, so call visit_circle.
return v.visit_circle(self)
@dataclass(frozen=True)
class Rect(Shape):
w: int
h: int
def accept(self, v: Visitor[R]) -> R:
return v.visit_rect(self)
class AreaVisitor(Visitor[float]):
def visit_circle(self, c: Circle) -> float:
return math.pi * c.r ** 2
def visit_rect(self, r: Rect) -> float:
return r.w * r.h
class SvgVisitor(Visitor[str]):
def visit_circle(self, c: Circle) -> str:
return f"<circle r='{c.r}'/>"
def visit_rect(self, r: Rect) -> str:
return f"<rect width='{r.w}' height='{r.h}'/>"
# Added later: a new operation is one new class.
# Circle, Rect and Visitor are not touched.
class PerimeterVisitor(Visitor[float]):
def visit_circle(self, c: Circle) -> float:
return 2 * math.pi * c.r
def visit_rect(self, r: Rect) -> float:
return 2 * (r.w + r.h)
def apply_all(shapes: list[Shape], v: Visitor[R]) -> list[R]:
# Dispatch 1: the shape's class picks which accept runs.
return [s.accept(v) for s in shapes]
if __name__ == "__main__":
shapes: list[Shape] = [Circle(1), Rect(2, 3)]
area = sum(apply_all(shapes, AreaVisitor()))
svg = "".join(apply_all(shapes, SvgVisitor()))
per = sum(apply_all(shapes, PerimeterVisitor()))
print(f"area: {area:.2f}") # area: 9.14
print(f"svg: {svg}")
# svg: <circle r='1'/><rect width='2' height='3'/>
print(f"perimeter: {per:.2f}") # perimeter: 16.28Key takeaways
- Visitor puts each operation over a structure in its own class; elements only implement
accept(v), which calls backv.visitX(this). - Double dispatch is two single-dispatch calls:
acceptis chosen by the element's class, thevisitmethod by the visitor's class, so the code that runs depends on both. acceptexists because overloads are resolved from static types; insideaccept, the element's exact type is known.- The trade-off is the expression problem: in the visualizer a new operation is 1 new class and 0 edits, while a new shape edits
Visitorand every visitor (3 classes). - Decide who walks the structure (elements, visitor or an iterator) and whether visitors return values or accumulate state.
- With sealed types and exhaustive pattern matching (Java 21, Kotlin, Rust, TypeScript unions,
std::variant), a plain function per operation is often the better tool.
Common pitfalls
- Using Visitor on a hierarchy that keeps growing: every new element type edits every visitor, which is the opposite of what you wanted.
- Calling an overloaded
visit(node)with a variable of the base type in Java or C++ and expecting run-time selection; overloads are picked at compile time. - Base visitors with silent do-nothing defaults: when a new element type arrives, visitors that should handle it ignore it without any error.
- Traversal in two places (elements visit children and visitors loop over them), so nodes are visited twice, or in neither, so subtrees are skipped.
- Making every element field public just so visitors can read it; expose only what operations genuinely need.
Interview tips
- Explain double dispatch with the two calls and a small grid of element types against visitors; then show why
visitor.visit(shape)with overloads does not compile in Java. - Frame the choice as the expression problem: Visitor makes operations cheap and types expensive, plain polymorphism the reverse.
- Use a compiler as the example (type checker, pretty printer and code generator as visitors over a stable syntax tree), and mention
ast.NodeVisitororjavax.lang.model. - Bring up pattern matching over sealed types as the modern alternative, and say when you would still choose Visitor.
Real-world applications
- Compilers, interpreters and linters: type checking, constant folding, pretty printing and code generation over a syntax tree.
- Document models exported to several formats (HTML, PDF, Markdown) from one tree of paragraphs, tables and images.
- Drawing and CAD programs: area, bounds, rendering and serialization over a fixed set of shapes.
- File system walkers that compute sizes, find files or copy trees (
Files.walkFileTree). - Annotation processors and code analysis tools that inspect classes, methods and fields.
- Rule engines and query optimizers that rewrite or analyze expression trees.
Test yourself
In the visualizer, right after the client calls circle.accept(area), which message comes next?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.