Visitor Pattern
The Visitor pattern moves an operation out of the classes it operates on. Every node type keeps one line of boilerplate – accept(visitor) – and every operation becomes its own class holding one method per node type. Adding a LaTeX renderer to a four-node expression tree stops being four edits across four working files and becomes one new file nothing else knows about.
💡 The expression problem = a class hierarchy makes a new TYPE cheap and a new OPERATION expensive, because a new subclass is one file while a new method is an edit to every subclass. Visitor inverts that exactly: a new operation is one file, a new type is an edit to every visitor. No mainstream object-oriented language gives you both cheaply, so the only design question is which axis will actually move.
Why this matters: Visitor is the pattern most often recited and least often understood, and interviewers know it. The mechanical half – accept calls visit, that is double dispatch, done – is memorised by everyone who has read a pattern list. What separates candidates is asking the question the pattern turns on: are the node types stable, and is the operation set what grows? Answer yes to both and Visitor is the right call. Reach for it when new node types keep arriving instead, and every new node breaks every visitor – the most common misuse, and what a good interviewer is probing for.
💡 Double dispatch = selecting behaviour from TWO runtime types at once – which node, and which operation. A normal virtual call selects from one.
Prerequisites
- Composite Pattern – a visitor almost always walks a Composite tree, and that leaf-and-container hierarchy is what the visitor’s method list mirrors
- Interpreter Pattern – Interpreter puts
evaluate()on the node itself, and Visitor is what you extract when a second and third operation show up - SOLID Principles – Visitor buys Open/Closed on operations by surrendering it on types, and knowing which half you traded is the lesson
The Problem: an expression AST where every node class grew five unrelated methods
An expression tree starts as four small classes – Number, Variable, Add, Multiply – each with one job: hold its part of the formula. Then the features arrive in the order they always do. Evaluate it. Print it back as readable text. Simplify it so x + 0 stops reaching the UI. List the variables a formula depends on, so the engine knows what to recompute. Render it as LaTeX for the docs page. Each is implemented the obvious way, as a method on Expression, so each lands on all four node classes.
// Expression declares all five -- evaluate, toInfix, simplify,
// collectVariables, toLatex -- so every node implements all five.
import java.text.DecimalFormat; // needed only by toLatex, imported anyway
import java.util.*;
public final class Number implements Expression {
private static final DecimalFormat LATEX = new DecimalFormat("#.####");
private final double value;
public Number(double value) { this.value = value; }
public double value() { return value; }
// One of these is the reason the class exists. The other four are here
// because an interface kept growing and every implementor had to follow.
@Override public double evaluate(Map<String, Double> env) { return value; }
@Override public String toInfix() { return String.valueOf(value); }
@Override public Expression simplify() { return this; }
@Override public Set<String> collectVariables() { return Set.of(); }
@Override public String toLatex() { return LATEX.format(value); }
}
public final class Add implements Expression {
private final Expression left, right;
public Add(Expression left, Expression right) { this.left = left; this.right = right; }
@Override public double evaluate(Map<String, Double> env) {
return left.evaluate(env) + right.evaluate(env);
}
@Override public String toInfix() {
return "(" + left.toInfix() + " + " + right.toInfix() + ")";
}
@Override public Set<String> collectVariables() {
Set<String> all = new HashSet<>(left.collectVariables());
all.addAll(right.collectVariables());
return all;
}
@Override public String toLatex() { return left.toLatex() + " + " + right.toLatex(); }
@Override public Expression simplify() { // x + 0 -> x
Expression l = left.simplify(), r = right.simplify();
if (l instanceof Number n && n.value() == 0.0) return r;
return (r instanceof Number n && n.value() == 0.0) ? l : new Add(l, r);
}
}
// Variable and Multiply look the same: five methods each, five unrelated jobs.
Three costs, in the order they bite:
- Cohesion is gone.
Numberwraps onedoubleand has five reasons to change: the evaluator, the printer, the simplifier, the dependency tracker and the LaTeX renderer all have a stake in it. Four of those five methods do nothing interesting – a number does not simplify and has no variables – so the class is mostly ceremony imposed from outside. - A new operation is an edit to four working classes. Shipping the pretty-printer means opening
Number,Variable,AddandMultiply, all currently passing their tests, to add one method each. Worse, the printer is then smeared across four files, so nobody can read the printing algorithm in one place – precedence especially, which is one algorithm cut into four pieces that must agree by convention. - The dependencies smear along with the methods. Evaluation needs a map and arithmetic; LaTeX rendering needs number formatting and escaping; simplification needs the node constructors. So
Number, a wrapper around onedouble, importsjava.text.DecimalFormat, and a change to the formatting library touches the core of your AST. That is the realistic cost: not that the class got long, but that unrelated libraries now reach into it.
Class Diagram
classDiagram
class Expression {
<<interface>>
+accept(visitor) R
}
class Number {
-double value
+accept(visitor) R
}
class Variable {
+accept(visitor) R
}
class Add {
-Expression left
-Expression right
+accept(visitor) R
}
class Multiply {
+accept(visitor) R
}
class ExpressionVisitor~R~ {
<<interface>>
+visitNumber(Number n) R
+visitVariable(Variable v) R
+visitAdd(Add a) R
+visitMultiply(Multiply m) R
}
class EvaluateVisitor {
-Map env
+visitAdd(Add a) Double
}
class PrintVisitor {
-int depth
+visitAdd(Add a) String
}
Expression <|.. Number
Expression <|.. Variable
Expression <|.. Add
Expression <|.. Multiply
ExpressionVisitor <|.. EvaluateVisitor
ExpressionVisitor <|.. PrintVisitor
Expression --> ExpressionVisitor
Add --> Expression
Multiply --> Expression
The non-obvious part is the cycle. Expression --> ExpressionVisitor because every node’s accept takes one, and ExpressionVisitor’s methods name Number, Variable, Add and Multiply by type, so the dependency runs both ways and the two files ship as one unit. That is the pattern’s bill: the visitor interface carries one method per concrete node type, so a fifth node type is a breaking change to every visitor that exists.
Real-World Example: Expression AST with pluggable operations
import java.util.*;
// One method per node type. Distinct names, not four overloads of visit(...);
// the reason is in the next section.
public interface ExpressionVisitor<R> {
R visitNumber(Number number);
R visitVariable(Variable variable);
R visitAdd(Add add);
R visitMultiply(Multiply multiply);
}
public interface Expression {
// R is on the METHOD, not on Expression. On the interface you would get
// Expression<Double> trees and Expression<String> trees, so one tree could
// serve only one operation -- this detail is what separates a usable
// Visitor from the textbook void version.
<R> R accept(ExpressionVisitor<R> visitor);
}
// One line of boilerplate per node, nothing else on it. Number shadows
// java.lang.Number here; production code would call it NumberLiteral.
public record Number(double value) implements Expression {
@Override public <R> R accept(ExpressionVisitor<R> v) { return v.visitNumber(this); }
}
public record Variable(String name) implements Expression {
@Override public <R> R accept(ExpressionVisitor<R> v) { return v.visitVariable(this); }
}
public record Add(Expression left, Expression right) implements Expression {
@Override public <R> R accept(ExpressionVisitor<R> v) { return v.visitAdd(this); }
}
public record Multiply(Expression left, Expression right) implements Expression {
@Override public <R> R accept(ExpressionVisitor<R> v) { return v.visitMultiply(this); }
}
// ---- Operation 1: evaluate. R = Double. State is the variable environment:
// read-only, carried across the whole traversal. ----
public final class EvaluateVisitor implements ExpressionVisitor<Double> {
private final Map<String, Double> env;
public EvaluateVisitor(Map<String, Double> env) { this.env = Map.copyOf(env); }
@Override public Double visitNumber(Number n) { return n.value(); }
@Override public Double visitVariable(Variable v) {
Double bound = env.get(v.name());
if (bound == null) throw new UnboundVariableException(v.name());
return bound;
}
// The recursion lives in the visitor, not the nodes: a parent asks its
// children to accept the same visitor, so all of "evaluate" is one file.
@Override public Double visitAdd(Add a) { return eval(a.left()) + eval(a.right()); }
@Override public Double visitMultiply(Multiply m) { return eval(m.left()) * eval(m.right()); }
private double eval(Expression child) { return child.accept(this); }
}
// ---- Operation 2: print. R = String off the SAME tree, which works only
// because accept is generic. State here is MUTABLE: the nesting depth, used to
// drop redundant brackets at the top level. ----
public final class PrintVisitor implements ExpressionVisitor<String> {
private int depth = 0;
@Override public String visitNumber(Number n) {
double v = n.value();
return v == Math.rint(v) ? String.valueOf((long) v) : String.valueOf(v);
}
@Override public String visitVariable(Variable v) { return v.name(); }
@Override public String visitAdd(Add a) { return binary(a.left(), "+", a.right()); }
@Override public String visitMultiply(Multiply m) { return binary(m.left(), "*", m.right()); }
private String binary(Expression left, String op, Expression right) {
depth++; // children render one level deeper
String rendered = left.accept(this) + " " + op + " " + right.accept(this);
depth--; // restore, or my sibling gets lied to
return depth == 0 ? rendered : "(" + rendered + ")";
}
}
// ---- Operation 3, to make the point: a third R, an entirely new pass, and
// not one node class changed. This class is the whole diff. ----
public final class CollectVariablesVisitor implements ExpressionVisitor<Set<String>> {
@Override public Set<String> visitNumber(Number n) { return Set.of(); }
@Override public Set<String> visitVariable(Variable v) { return Set.of(v.name()); }
@Override public Set<String> visitAdd(Add a) { return union(a.left(), a.right()); }
@Override public Set<String> visitMultiply(Multiply m) { return union(m.left(), m.right()); }
private Set<String> union(Expression l, Expression r) {
Set<String> all = new TreeSet<>(l.accept(this)); // sorted, so a before b
all.addAll(r.accept(this));
return all;
}
}
// ---- One tree, three return types ----
Expression ast = new Multiply(new Variable("a"),
new Add(new Variable("b"), new Number(2)));
double value = ast.accept(new EvaluateVisitor(Map.of("a", 3.0, "b", 4.0))); // 18.0
String text = ast.accept(new PrintVisitor()); // a * (b + 2)
Set<String> vars = ast.accept(new CollectVariablesVisitor()); // [a, b]
from dataclasses import dataclass
from functools import singledispatchmethod
from typing import assert_never # 3.11+; before that, raise TypeError
node = dataclass(frozen=True, slots=True) # immutable, hashable AST nodes
@node
class Number:
value: float
@node
class Variable:
name: str
@node
class Add:
left: "Expression"
right: "Expression"
@node
class Multiply:
left: "Expression"
right: "Expression"
Expression = Number | Variable | Add | Multiply
# ---- Form 1: singledispatchmethod. The dispatch table a Java visitor writes
# out by hand, built by the library instead -- and no accept on any node. ----
class Evaluate:
def __init__(self, env: dict[str, float]) -> None:
self._env = dict(env) # state carried across the whole walk
@singledispatchmethod
def visit(self, node: Expression) -> float:
# Reached only for a node type nobody registered: the runtime version
# of the omission an exhaustive match catches before shipping.
raise TypeError(f"no visit registered for {type(node).__name__}")
@visit.register
def _(self, node: Number) -> float: return node.value
@visit.register
def _(self, node: Variable) -> float: return self._env[node.name]
@visit.register
def _(self, node: Add) -> float:
return self.visit(node.left) + self.visit(node.right)
@visit.register
def _(self, node: Multiply) -> float:
return self.visit(node.left) * self.visit(node.right)
# ---- Form 2: structural pattern matching, 3.10+. One function you can read in
# one go, and no class per operation at all. ----
def to_infix(node: Expression) -> str:
match node:
case Number(value=v):
return str(int(v)) if v.is_integer() else str(v)
case Variable(name=n):
return n
case Add(left=l, right=r):
return f"{to_infix(l)} + {to_infix(r)}"
case Multiply(left=l, right=r):
bracket = lambda x: f"({to_infix(x)})" if isinstance(x, Add) else to_infix(x)
return f"{bracket(l)} * {bracket(r)}"
case _:
# mypy flags a missing case HERE, at type-check time. At runtime
# this just raises, which is the best Python offers.
assert_never(node)
ast = Multiply(Variable("a"), Add(Variable("b"), Number(2)))
Evaluate({"a": 3.0, "b": 4.0}).visit(ast) # 18.0
to_infix(ast) # 'a * (b + 2)'
# Why the classic accept/visit pair is rare in Python: dispatch never needed a
# compile-time hook. isinstance, a dict keyed by type, singledispatch and match
# all pick the branch at runtime, so accept would buy one thing only -- letting
# a node class from someone else's package join in.
#include <memory>
#include <string>
#include <unordered_map>
#include <variant>
struct Number { double value; };
struct Variable { std::string name; };
struct Add;
struct Multiply;
using Env = std::unordered_map<std::string, double>;
// unique_ptr may name an incomplete type, which is what makes the recursion
// legal: Expression is complete before Add and Multiply are defined.
using Expression = std::variant<Number, Variable,
std::unique_ptr<Add>, std::unique_ptr<Multiply>>;
struct Add { Expression left, right; };
struct Multiply { Expression left, right; };
// The overload set: lambdas fused into one callable with one operator() per
// node type. This IS the visitor, in two lines of template.
template <class... Fs> struct overload : Fs... { using Fs::operator()...; };
template <class... Fs> overload(Fs...) -> overload<Fs...>; // C++17 needs this
double evaluate(const Expression& e, const Env& env) {
return std::visit(overload{
[](const Number& n) -> double { return n.value; },
[&](const Variable& v) -> double { return env.at(v.name); },
[&](const std::unique_ptr<Add>& a) -> double {
return evaluate(a->left, env) + evaluate(a->right, env); },
[&](const std::unique_ptr<Multiply>& m) -> double {
return evaluate(m->left, env) * evaluate(m->right, env); }
}, e);
}
// The idiomatic modern C++ answer, and it beats accept-plus-visit twice over.
// Forget a lambda after adding a node type and you get a COMPILE error, not a
// silent fallthrough. And std::visit takes any number of variants, so
// std::visit(f, a, b) is GENUINE double dispatch: the library generates the
// N x M table that accept-plus-visit spells out by hand.
Where the state lives, because that is the first follow-up. EvaluateVisitor takes its environment in the constructor and never writes to it, so one instance is reusable. PrintVisitor mutates depth as the walk descends, the common shape for anything positional – indentation, operator precedence, a breadcrumb path – and it carries two rules: restore the old value on the way out, or a sibling subtree inherits the wrong context, and treat the visitor as single-use per traversal, not a shared service. The cleaner alternative is a second type parameter, ExpressionVisitor<R, C> with R visitAdd(Add a, C context), which threads context explicitly and keeps the visitor stateless. ANTLR’s generated visitors offer both shapes for this reason.
Double dispatch, and why the language makes you write it by hand
A normal virtual call dispatches on one runtime type: the receiver. expression.evaluate(env) looks up evaluate in the vtable of whatever expression turns out to be. That is single dispatch, and it is all Java, C# and C++ give you for free.
Visitor needs behaviour selected by two types – which node you are at, and which operation you are running – and neither is known at the call site. So it simulates one two-type lookup with two one-type lookups in a row:
ast.accept(printVisitor)is a virtual call onast, so the runtime type wins: ifastis anAdd,Add.acceptruns. First dispatch: the node type is resolved.- Inside
Add.acceptthe body isvisitor.visitAdd(this), a virtual call onvisitor, soPrintVisitor.visitAddruns. Cruciallythisis statically typed asAddhere, which is what lets the compiler pick theAdd-shaped method at all. Second dispatch: the operation is resolved.
Two single dispatches compose into one double dispatch, and the nodes contribute the one thing only they can: their own concrete type.
The cost of doing it with overloads. If ExpressionVisitor declares four methods all named visit, the choice between them is made at compile time from the static type of the argument. Add a convenience visit(Expression) and forget visit(Multiply), and the call inside Multiply.accept quietly binds to the general overload: it compiles, it runs, and multiply is handled by the catch-all. Distinct names – visitAdd, visitNumber – remove the hazard, because a missing method is then a compile error at every implementing class.
The modern alternative, stated honestly
Three languages now do this directly, with the compiler checking what you were checking by hand. In Java 21 you declare sealed interface Expression permits Number, Variable, Add, Multiply and write each operation as a switch over record patterns – case Add(Expression l, Expression r) -> evaluate(l, env) + evaluate(r, env) – with no default branch, because the switch is exhaustive over the permits clause. No accept, no visitor interface, and a fifth node type stops every such switch compiling. Python 3.10’s match reads the same way, with typing.assert_never recruiting the type checker for exhaustiveness. C++ has had std::variant plus std::visit since C++17, and that one is strongest: std::visit over two variants is genuinely double dispatch rather than a simulation of it.
Say this out loud in an interview. Where you own the hierarchy and can seal it, sealed-plus-switch is usually the better answer than Visitor – fewer files, no boilerplate, exhaustiveness enforced by the compiler instead of by code review, and saying so shows you choosing the pattern rather than reciting it. Visitor stays correct in two cases: a hierarchy deliberately open to extension by other modules, where no permits clause can exist and accept is the only hook a foreign node type arrives through; and generated or third-party types that already carry accept – ANTLR parse trees, Eclipse JDT ASTs – where you will write visitors whether you chose the pattern or not.
Visitor vs Interpreter vs Iterator vs Composite vs Strategy
Four of these five turn up in the same tree-shaped problem. The separator is which part of the job each owns:
| Pattern | Intent | Tell |
|---|---|---|
| Visitor | Add an operation across a fixed set of node types without editing them | One method per node type – visitAdd, visitNumber – plus accept on every node |
| Interpreter | Give each node type the behaviour for evaluating itself | The operation is a method on the node – node.evaluate(context) – with no operation object |
| Iterator | Walk an aggregate without exposing how it stores elements | A cursor plus hasNext / next; it owns the order, not what happens at a node |
| Composite | Let a container and a leaf share one interface | It defines the shape; the tree exists before anyone walks it |
| Strategy | Swap one algorithm behind one interface | One method, no per-type methods, no type hierarchy in sight |
One sentence to keep them apart: Composite defines the tree, Iterator defines the walk over it, and Visitor defines what happens at each node. Those three compose rather than compete, and the trio is standard – Expression Evaluator and Spreadsheet Engine use all three at once.
Interpreter is the interesting neighbour, because Visitor is usually what you extract from it. Interpreter is the version in “The Problem” above – evaluate() on each node – which is genuinely right while evaluation is the only operation and is intrinsic to what a node means. When the second and third pass arrive, you move all of them out and the nodes keep only accept. Strategy is the odd one out: a “visitor” with a single visit(Object) is a Strategy and should be named one.
When to Use vs When to Avoid
| Use Visitor When | Avoid When |
|---|---|
| Node types are stable and operations keep multiplying – ASTs, document trees, config schemas | New node types arrive more often than new operations |
| One operation’s logic belongs in one readable file – type checker, printer, cost estimator | You own the hierarchy and the language has sealed types plus exhaustive matching |
| Operations have different dependencies – rendering needs a formatter, evaluation does not | One operation, intrinsic to the node, so Interpreter is simpler |
| Operations ship from outside the hierarchy’s module – a linter plugin, a separate jar | The operation needs node internals and would drag getters onto every node |
| You need a differently typed result per operation off one tree | Two node types and one operation, where a switch is honest and shorter |
The characteristic failure mode is Visitor applied to a type set that keeps growing. Each new node type is a new method on the visitor interface, which breaks every implementation at once, so with four visitors in the codebase adding one node type is five edits – three of them throw new UnsupportedOperationException("no rule for Modulo"), because three of those passes have no opinion about the new node. The pattern has inverted into the expensive direction, and nobody notices until the fifth node type.
The usual mitigation is a default method on the interface, or an abstract base visitor full of no-ops, so a new node type compiles everywhere. This is a trap, and explaining why is worth more than knowing the mitigation: it converts a loud compile error into a silent behavioural gap, so Modulo is quietly skipped by the printer and the dependency tracker, and you find out when a formula renders with a piece missing. If you take that route, make the default throw rather than return something plausible.
The second failure mode is quieter. A visitor that needs a node’s private state forces accessors onto it – the serializer wants the raw cached value, the optimizer wants an internal flag – and within a few passes every node is a bag of public getters, so the pattern meant to protect node classes from unrelated operations has stripped their encapsulation instead. The test is whether accept is still the only interesting thing on a node; if one carries eleven getters so six visitors can reach inside, either that data belongs in a separate structure the visitors own, or those visitors belong back on the node.
Interview Questions
-
“Explain double dispatch and where Visitor uses it.” – A virtual call picks an implementation from one runtime type, the receiver, and Visitor needs behaviour chosen from two: which node and which operation. So it chains two single dispatches –
node.accept(v)resolves the node type, thenv.visitAdd(this)resolves the visitor type whilethisis statically known to beAdd, which is what lets the compiler bind the node-shaped method. Neither call alone is double dispatch; the composition is. C++ does it for real withstd::visitover two variants, where the library generates the N x M table. -
“When is Visitor the wrong choice?” – When the type set is what grows. This is the expression problem: a class hierarchy makes new types cheap and new operations expensive, and Visitor flips that trade rather than removing it, so you only win when operations are the moving part and the node types are frozen. On a hierarchy that gains a type every sprint, every new type breaks every visitor, and the honest fix is deleting the pattern rather than papering over the gap with no-op defaults.
-
“Do sealed interfaces and pattern matching make Visitor obsolete?” – Where you own the hierarchy and can seal it, mostly yes, and I would default to sealed-plus-switch in Java 21: operations become plain functions and a new node type breaks compilation at every switch, which beats the review discipline Visitor depends on. Two cases keep it alive – a hierarchy intentionally open to extension by other modules, where no
permitsclause can exist, and generated types that already shipaccept, like ANTLR trees or JDT ASTs. -
“How does a visitor accumulate a result across a whole tree?” – Three options, and I would pick the first. A generic return type (
ExpressionVisitor<R>, eachvisitcombining its children’s results) makes the traversal a fold – each parent computes its children’s values and combines them – so there is no shared mutable state and the instance stays reusable. A mutable accumulator field is justified only when the result is genuinely a sink, appending to aStringBuilderor writing to a stream, and then the visitor is single-use and should refuse a second traversal rather than return a doubled result. Threading an explicit context parameter is the third, for when children need information from above. -
“The structure is a cyclic graph, not a tree. What changes?” – You add a visited set and check it at the top of each
visit, or the traversal never terminates. The subtlety is that the set must use identity, notequals: in a graph with value-equal nodes, two structurally identical nodes are legitimately different vertices, soCollections.newSetFromMap(new IdentityHashMap<>())is the right container and a plainHashSetsilently prunes real subgraphs. That set is per-traversal state, so the visitor stops being reusable – construct one per walk, or pass the set in as context. Memoising on a DAG is correct for a pure visitor and wrong for a side-effecting one, which then fires once instead of once per path.
See It in Action
- Expression Evaluator – the AST above, with evaluate, print and variable-collection passes over the same four node types
- Spreadsheet Engine – formula ASTs visited for evaluation, for the dependency edges that drive recalculation, and for rewriting references when a row is inserted
- File Search – one visitor per pass over the
FileandDirectoryComposite: size totals, match predicates, permission audits - Mini Version Control – tree objects visited to diff, to materialise a checkout, and to find unreachable objects during collection