A calculator holds (x + 2) * (y + -3) as a tree. The multiply sits at the top, the two additions hang under it, and the numbers and letters sit at the leaves. The calculator asks this tree several different questions. What is its value when x is 4 and y is 10? How should it be printed? Can it be written more simply?
Each question has to do something different for each kind of node. Evaluating an add adds two numbers. Printing an add writes a plus sign between two pieces of text. Simplifying an add can drop a + 0. The same shape shows up in a compiler, which type-checks, optimises and generates code over one syntax tree, and in a document, which is counted, spell-checked and exported over one tree of paragraphs and tables.
The Visitor pattern puts each question in its own class, with one method per kind of node. In this article we build a small calculator twice. The first version answers each question with a chain of type checks. The second uses the Visitor pattern. Then we look at what the pattern costs, when a switch over sealed types is the better tool in modern Java, and how this shows up in interviews.
All the code is Java. The snippets come from two complete projects, the first version and the finished one, apart from a few short sketches that are labelled. Both projects compile, and the finished one runs. The Open file button on a snippet from the finished project shows the whole file in a code browser.
The calculator we are building
The calculator works on whole numbers. An expression is a tree of six kinds of node:
- a number, such as
2or-3; - a variable, such as
x; - add, multiply and divide, each with a left and a right child;
- negate, with one child.
It must answer three questions about any tree:
- Evaluate it, given a value for each variable. Division rounds toward zero, as Java's
/does. - Print it with the fewest brackets that still show the tree's exact shape.
- Simplify it: fold constants (
2 + 3becomes5) and drop steps that change nothing (x * 1becomesx,y + 0becomesy).
Mistakes in the input, such as an unknown variable, a division by zero or a result too large for a long, must produce a message a person can read. A tree too deep to walk safely must be refused when it is built.
The first version: a type check in every question
The obvious way to write this is one method per question, each with a chain of instanceof checks that picks the right code for the node in hand:
public static long evaluate(Expr expr, Map<String, Long> values) { if (expr instanceof Num number) { return number.value(); } else if (expr instanceof Var variable) { return values.get(variable.name()); } else if (expr instanceof Add add) { return evaluate(add.left(), values) + evaluate(add.right(), values); } else if (expr instanceof Multiply multiply) { return evaluate(multiply.left(), values) * evaluate(multiply.right(), values); } else if (expr instanceof Divide divide) { return evaluate(divide.left(), values) / evaluate(divide.right(), values); } else if (expr instanceof Negate negate) { return -evaluate(negate.operand(), values); } throw new IllegalArgumentException("Unknown node: " + expr); }print and simplify have the same kind of chain. For a calculator with six kinds of node and three questions, this code works and is easy to follow. The trouble comes as it grows.
Every question repeats the same dispatch. Each method starts by asking "which kind of node is this?", and each asks it in its own words. The three chains drift apart over time.
The compiler does not notice a missing case. The first version's print has five branches, and none of them is for divide. The code compiles, and printing x / 2 fails at run time with "Unknown node". The same happens to every chain when a new kind of node, such as a power, is added and one chain is forgotten.
A chain can miss a case with no error at all. simplify ends with return expr for any node it does not handle. Its divide branch never folds 8 / 2, and a new power node would pass through unsimplified, with no error anywhere. evaluate and print at least end in a throw, so their missing cases fail when they run.
There is a second obvious design: give every node class one method per question, so Add has evaluate, print and simplify. Then no type checks are needed. But each new question now means editing all six node classes, and the evaluation, printing and simplifying code is spread across six files.
This is the same grid the State pattern page draws for states and actions. The right cut depends on which way the grid will grow. A calculator's node kinds are fixed by arithmetic. Its questions keep coming: count the variables, find the derivative, check the types, compile to bytecode. When the questions grow and the node kinds do not, each question should be one class.
The idea
The pattern works like this:
- Each question becomes a visitor class, with one method per kind of node:
visitAdd,visitMultiplyand so on. - Each node class gets one method,
accept(visitor). It calls the visitor method for its own kind and passes itself:Addcallsvisitor.visitAdd(this). - To ask a question, a caller passes a visitor to the root:
tree.accept(evaluator). The visitor's methods carry on down the tree by callingaccepton the children.
The node classes no longer know any question. A new question is one new visitor class, and the nodes do not change.
The pattern's parts have names. The node classes are the elements, ExprVisitor is the visitor interface, and Evaluator, Printer and Simplifier are the concrete visitors.
The tree itself is built from one more pattern.
Building it, step by step
Step 1: one interface for every question
ExprVisitor has one method per kind of node:
Every visitor must implement all six methods, or it does not compile. This is the check the first version did not have. A new kind of node means a seventh method here, and then the compiler lists every visitor that has not handled it.
The type parameter R is what the visitor gives back. The evaluator returns a Long, the printer a String and the simplifier a new Expr.
What does a visitor give back?
Nothing: each visitor keeps its answer in a field
The visitor methods return void. The evaluator pushes numbers onto a stack field, and the printer appends to a StringBuilder field. This works without generics. But the visitor now has state, so one evaluator cannot safely evaluate two trees at once, and every method has to remember to push and pop in the right order.
A value: the type parameter ROur pick
Each visit method returns its answer, and a parent combines its children's answers. The evaluator's visitAdd adds two returned numbers. The visitors keep no state from one call to the next, apart from the evaluator's variable values, which never change. The cost is a boxed Long for every node the evaluator visits, which is small for a calculator.
Step 2: accept on every node
Every node class has the same short accept method. Here is the one on Add:
public final class Add implements Expr { private final Expr left; private final Expr right; private final int depth; public Add(Expr left, Expr right) { this.left = Objects.requireNonNull(left, "left"); this.right = Objects.requireNonNull(right, "right"); this.depth = Depth.above(left, right); } public Expr left() { return left; } public Expr right() { return right; } @Override public <R> R accept(ExprVisitor<R> visitor) { return visitor.visitAdd(this); } @Override public int depth() { return depth; }}accept looks pointless at first. A caller could surely call evaluator.visitAdd(add) directly. But a caller holding a tree only knows it has an Expr, not which kind. Java picks between overloads by the argument's compile-time type, not the object's real class:
void visit(Add add) { ... }void visit(Expr expr) { ... } Expr expr = new Add(x, y);visit(expr); // calls visit(Expr), not visit(Add)accept fixes this with two calls in a row. The first call, expr.accept(visitor), is chosen by the node's real class, because accept is an ordinary overridden method. Inside Add.accept, the type of this is Add, so the second call goes to visitAdd, which is chosen by the visitor's real class. Two choices made at run time, one for the node and one for the visitor, are why the trick is called double dispatch.
We name the methods visitAdd, visitMultiply and so on, rather than six overloads all called visit. Overloads would work inside accept, but they invite exactly the mistake in the sketch above, where a reader expects the call to pick the right one by itself.
Step 3: evaluate
The evaluator holds the variable values and answers one node at a time:
@Override public Long visitAdd(Add add) { long left = add.left().accept(this); long right = add.right().accept(this); try { return Math.addExact(left, right); } catch (ArithmeticException overflow) { throw tooLarge(); } } @Override public Long visitMultiply(Multiply multiply) { long left = multiply.left().accept(this); long right = multiply.right().accept(this); try { return Math.multiplyExact(left, right); } catch (ArithmeticException overflow) { throw tooLarge(); } } @Override public Long visitDivide(Divide divide) { long left = divide.left().accept(this); long right = divide.right().accept(this); if (right == 0) { throw new EvaluationException("Division by zero"); } if (left == Long.MIN_VALUE && right == -1) { throw tooLarge(); } return left / right; }visitAdd first asks each child for its value, by calling accept(this) on it. Then it adds the two numbers with Math.addExact, which throws instead of quietly wrapping round when the sum is too large for a long. visitDivide checks the divisor before dividing, and also refuses the one division that overflows: the smallest long divided by -1.
Where does the walk down the tree happen?
Inside accept: each node visits its children first
Add.accept would call left.accept(visitor) and right.accept(visitor) before visitor.visitAdd(this). Every visitor gets the same walk for free. But then every question walks the tree in one fixed order, and a visitor cannot skip a subtree, combine its children's answers, or decide on brackets before it sees the children.
Inside the visitor: each visit method calls accept on the childrenOur pick
The visitor decides what to visit and when. The evaluator needs both children's values before it can add them. The printer needs to know each child's precedence before it writes it. The simplifier needs its children simplified first. Each of these is one line in the visitor, and accept stays a single call.
The evaluator also has to say what goes wrong.
What happens when an expression cannot be evaluated?
Return an empty value
evaluate could return an empty optional for a missing variable or a division by zero. But the caller would not learn which one went wrong, and every visit method would have to check its children's answers before using them.
Throw one exception with a message for a personOur pick
A missing variable, a division by zero and a result too large for a long all come from what a person typed. Each throws an EvaluationException whose message can go straight to the screen: "z has no value", "Division by zero", "Result is too large". Mistakes in our own code are different. A null child, a variable named 2x or a tree too deep to walk throws a NullPointerException or IllegalArgumentException when the node is built. A parser that builds trees from typed text would catch those and turn them into its own message.
The evaluator takes its variable values as a map and keeps a copy, made with Map.copyOf in its constructor. The copy refuses null names and values, and a caller who changes their own map later does not change the evaluator's answers.
Step 4: print with only the brackets the shape needs
The printer gives each kind of node a precedence: sums lowest, then products, then a minus sign, then numbers and variables. A child gets brackets when its precedence is too low for its parent:
@Override public String visitAdd(Add add) { return binary(add.left(), " + ", add.right(), SUM); } @Override public String visitMultiply(Multiply multiply) { return binary(multiply.left(), " * ", multiply.right(), PRODUCT); } @Override public String visitDivide(Divide divide) { return binary(divide.left(), " / ", divide.right(), PRODUCT); } @Override public String visitNegate(Negate negate) { Expr operand = negate.operand(); return "-" + inBracketsIf(operand, precedenceOf(operand) <= SIGN); } // a + b + c reads as (a + b) + c, so a left child at the same level needs no brackets and a right child does. private String binary(Expr left, String operator, Expr right, int level) { return inBracketsIf(left, precedenceOf(left) < level) + operator + inBracketsIf(right, precedenceOf(right) <= level); }Java reads a + b + c as (a + b) + c. So the printer leaves out brackets on a left child at the same level, and keeps them on a right child at the same level. The tree for x + (y + 1) prints with its brackets, and the tree for (x + y) + 1 prints as x + y + 1. Each printout shows exactly one tree, with one exception: a negate of a positive number and the matching negative number, such as a negated 5 and -5, print the same. They have the same value, so the printer keeps the shorter form.
The printer needs a second question for this, "what is this node's precedence?". That question also depends on the kind of node, so it is a second visitor, Precedence, nested inside the printer. A negative number such as -5 counts as a minus sign, so -(-5) keeps its brackets and never prints as --5.
Step 5: simplify
The simplifier returns a new tree. Here is its add:
@Override public Expr visitAdd(Add add) { Expr left = add.left().accept(this); Expr right = add.right().accept(this); OptionalLong a = constantOf(left); OptionalLong b = constantOf(right); if (a.isPresent() && b.isPresent()) { try { return new Num(Math.addExact(a.getAsLong(), b.getAsLong())); } catch (ArithmeticException overflow) { return new Add(left, right); } } if (isConstant(left, 0)) { return right; } if (isConstant(right, 0)) { return left; } return new Add(left, right); }It simplifies both children first, so (x * 1 + 0) has already become x before its parent looks at it. If both children are now numbers, it folds them into one number. If the sum would overflow, it leaves the add as it is, and evaluating it later gives the "Result is too large" message. Then it drops a 0 on either side.
To ask "is this child a number?", the simplifier uses instanceof:
visitNegate asks one more such question, whether its operand is itself a negate, to turn -(-x) into x. The first version's problem was asking "which of the six kinds is this?" in every method. These are yes-or-no questions about one kind each, about a child rather than the node being visited, and a whole visitor for each would be heavier than the check.
May simplify turn a failure into an answer?
Never: the simplified tree fails exactly when the original does
Then x * 0 cannot become 0, because the original fails when x has no value and 0 does not. The simplifier could only fold constants and drop + 0 or * 1, and the most familiar rule of all, anything times zero is zero, would be off limits.
Only keep every answer the original hasOur pick
The simplified tree gives the same answer wherever the original gives one. Simplify never folds a failing step itself: 7 / 0 and an overflowing MAX * 2 stay as they are. But two rules can drop a part that would have failed. Anything times zero becomes zero, so (1 / 0) * 0 becomes 0, and -(-x) becomes x, even where negating x would overflow. A tree that fails may therefore simplify to one that does not.
Simplifying never makes a tree deeper, so a simplified tree can always be built.
Step 6: how deep can a tree go?
Every visitor walks the tree with recursion. Each level uses at least two stack frames, one for accept and one for the visit method, so a tree thousands of levels deep would end in a StackOverflowError. Every node therefore records its depth when it is built, and refuses to be built past 1,000 levels:
A node's depth is one more than its deepest child's (line 12), so building a tree costs one step per node, not one walk of the tree. The check runs once, in the constructor, so no visitor needs its own guard. Expr is a sealed interface that only the six node classes may implement, so no outside class can report a depth of 0 and slip past the limit.
The limit protects the stack, not time or memory. One node can be the child of several parents, so e = new Add(e, e), repeated 28 times, builds a tree only 29 levels deep that the visitors see as hundreds of millions of nodes. A calculator that builds trees from typed text does not share nodes like this; one that accepts trees from other code would also cap the number of nodes.
The Composite pattern page makes the same choice for folders, with a lower limit of 256 levels, chosen as more than any realistic folder tree needs. A calculator's limit is set by the stack instead: each level here costs at least two frames. On a small 512 KB thread stack, evaluate overflowed at about 2,500 levels, the lowest of the three visitors, so 1,000 levels leave room to spare, and Java's usual 1 MB default leaves more.
The finished design
Here is one evaluation of x + 2, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package expr; public interface ExprVisitor<R> { R visitNumber(Num number); R visitVariable(Var variable); R visitAdd(Add add); R visitMultiply(Multiply multiply); R visitDivide(Divide divide); R visitNegate(Negate negate);}The demo in demo/Main.java asks the three questions of one tree, then shows each rule at work:
1. One tree, three questions (x = 4, y = 10) print (x + 2) * (y + -3) evaluate 42 simplify (x + 2) * (y + -3) 2. Simplify (x * 1 + 0) * (2 + 3) becomes x * 5 -(-x) becomes x y * 0 becomes 0 3. Brackets only where the tree needs them x + y + 1 x + (y + 1) x * (y / 2) x * y / 2 -(x + 1) 4. Mistakes in the input x / (y + -10): Division by zero z + 1: z has no value 9223372036854775807 * 2: Result is too large simplify 9223372036854775807 * 2 (left as it is) 5. A deep tree 1000 levels evaluate to -4 one more level: Expression is deeper than 1000 levels
The first tree evaluates to 42, and simplify brings it back unchanged, because none of its parts are constants it can fold. The second block shows the folding rules, including y * 0 becoming 0. The third block shows that x + y + 1 and x + (y + 1) print differently, because they are different trees. The fourth block shows the three mistakes a person can make, and that simplify leaves the overflowing multiply alone. The last block builds a tree exactly 1,000 levels deep, evaluates it, and is refused one level more.
What it costs
The pattern makes one kind of change cheap and another expensive.
Adding a question is cheap. Counting the variables is one new class that implements ExprVisitor. No node class changes.
Adding a kind of node is expensive. A power node, x ^ 2, needs a new class, an entry in Expr's permits list and a seventh method on ExprVisitor. Then every visitor must implement it: the evaluator, the printer, its precedence visitor and the simplifier.
There are smaller costs too. Every node class carries an accept method that does nothing but forward. A visitor can only see what the node classes make public, so left(), right() and operand() exist for the visitors' sake. And following one evaluation means jumping between the node and the visitor, as the trace above shows.
When a switch is better
Java offers a way to get the visitor's main benefit without accept. A sealed interface, added in Java 17, lists every class allowed to implement it; our Expr is already one. Since Java 21, a switch over a sealed type must cover every one of those classes, or it does not compile:
sealed interface Expr permits Num, Var, Add, Multiply, Divide, Negate {} record Num(long value) implements Expr {}record Add(Expr left, Expr right) implements Expr {}// Var, Multiply, Divide and Negate are records too long evaluate(Expr expr) { return switch (expr) { case Num number -> number.value(); case Var variable -> valueOf(variable.name()); case Add add -> Math.addExact(evaluate(add.left()), evaluate(add.right())); case Multiply multiply -> Math.multiplyExact(evaluate(multiply.left()), evaluate(multiply.right())); case Divide divide -> divide(evaluate(divide.left()), evaluate(divide.right())); case Negate negate -> Math.negateExact(evaluate(negate.operand())); };}Each question is one method with one switch. If a power node is added to the permits list, every switch that does not handle it stops compiling, which is the same safety the visitor interface gives. There is no accept, no visitor interface and no double dispatch to explain. The safety holds only while the switch has no default branch. A default catches the new node kind silently, and the code compiles.
The switch is the better choice when the code runs on Java 21 or later and the node classes are yours to seal. The Visitor pattern itself needs only generics; this project uses Java 17 for sealed. The Visitor pattern still fits in three cases. The code must run on older Java, or the library already gives its nodes an accept method and a visitor interface, or a question must be an object that can be passed around, stored or swapped.
Visitor or a switch over sealed types?
| Visitor | Switch over sealed types | |
|---|---|---|
| Java version | Any with generics (this project uses 17, for sealed) | 21 or later |
| A new question | One new visitor class | One new method with a switch |
| A new kind of node | A method on the interface and in every visitor | A case in every switch |
| Does the compiler catch a missing case | Yes, through the interface | Yes, through the sealed list |
| Extra code per node | An accept method | None |
| The question as an object | Yes, a visitor can be passed around | No, it is a method |
A short way to say it: both answer "a fixed set of node kinds, a growing list of questions"; the switch does it with less code where the language allows.
The Iterator pattern page draws the line between the two in one sentence: an iterator decides the order of a walk, and a visitor decides what to do with each kind of item. Our visitors do their own walking, so the calculator has no iterator.
In an interview
The Visitor pattern sits inside questions about expression evaluators, compilers and document export. It also fits a shopping cart that needs a tax, a discount and a shipping weight for each kind of item. The shape to look for is a tree of a few kinds of thing and a list of operations that keeps growing.
We suggest presenting it in this order:
- Draw the grid of questions and node kinds. Say which way it will grow. If node kinds are fixed and questions grow, a visitor fits. If node kinds grow, put the questions on the nodes.
- Write the visitor interface and one
accept, then explain double dispatch in two sentences: the first call picks the node's real class, the second picks the visitor's. - Write one visitor in full, usually evaluate, and say where the recursion lives and what happens on bad input.
- Mention the sealed switch if the interview is in Java 21 or later, and say when you would choose it instead.
Common mistakes:
- A visitor that still checks types. If a visit method asks
instanceofabout its own node, the dispatch is not doing its job. - Overloads named
visitfor every kind, called from outsideaccept. The compiler picks the overload by the static type, so the call quietly goes to the general one. - State in a visitor that should not have any. A printer that appends to a field cannot print two trees at once and gives wrong text if it is reused. Return values instead.
- A
defaultbranch in a switch over sealed types. It turns off the check that every kind is covered, so a new node kind compiles and falls into the default. - No plan for bad input. An unknown variable that silently becomes 0, or a division by zero that surfaces as Java's own
ArithmeticException, leaves the caller without a message to show. - A visitor where the node kinds keep growing. Every new node means editing every visitor. In that case the questions belong on the nodes.
Summary
- Use the Visitor pattern when a tree has a fixed set of node kinds and the list of questions about it keeps growing.
- Each question is one visitor class with a method per node kind. Each node has one
acceptmethod that calls the method for its own kind. acceptexists because Java picks overloads by static type. Two calls, double dispatch, reach the right method for both the node and the visitor.- Let visitors return values, keep the recursion in the visitor, and decide which errors are messages for a person.
- Adding a question is cheap. Adding a kind of node touches every visitor.
- On Java 21 and later, a sealed interface and a
switchgive the same compile-time check with less code.