Scrivio Interview library
DesignIntermediate8 min read · updated 12 November 2026

Compare the visitor pattern with sealed interfaces and switch pattern matching in Java 21 for adding operations to an AST of expression nodes. When is visitor still the better choice?

The visitor pattern adds operations to a fixed set of node classes through double dispatch: each node's accept() calls the matching visit method, so a new operation is a new visitor class and the nodes never change. In Java 21, a sealed interface plus an exhaustive switch with record patterns gives the same benefit with far less code, and the compiler flags every switch that misses a new node type. Visitor is still the better choice when the hierarchy cannot be sealed because other modules add nodes, when many operations share one traversal, or when a library must support Java versions older than 21.

Why this question is asked

Expression trees appear in more places than compilers: rule engines, query builders, pricing formulas, search filters and template languages all build a tree of nodes and then run several operations over it, such as evaluating, printing, validating and optimising. For twenty years the textbook answer in Java was the visitor pattern. Since Java 21, sealed interfaces and pattern matching for switch offer a second answer, and interviewers want to know whether we understand what each one really buys us rather than which one is fashionable. In this answer, we will build a small expression tree both ways, see how double dispatch works, look at what happens when a new node or a new operation arrives, and then name the situations where visitor still wins.

1A Quick Recap of the Problem

An AST, an abstract syntax tree, is a tree of objects that represents an expression. The expression 2 + 3 * 4 becomes an Add node whose left child is the number 2 and whose right child is a Mul node holding 3 and 4. Each kind of node is a class, and the tree is built from instances of those classes.

We want to run several operations over the tree. Evaluation returns 14. Printing returns the text (2 + (3 * 4)). A simplifier might turn x * 1 into x. The question is where the code for each operation lives. If we put an eval() method, a print() method and a simplify() method on every node class, every new operation forces us to edit every node class, and the logic of one operation is scattered across many files. This tension between adding new types and adding new operations is often called the expression problem, and both techniques in this answer are ways of choosing which side is cheap.

2How the Classic Visitor Works

The visitor pattern moves each operation into its own class, a visitor, which has one visit method per node type. Each node gets a single accept() method that hands itself to the visitor.

Java
interface Expr { <R> R accept(ExprVisitor<R> v); }
interface ExprVisitor<R> {
R visitNum(Num n);
R visitAdd(Add a);
R visitMul(Mul m);
}
final class Num implements Expr {
final int value;
Num(int value) { this.value = value; }
public <R> R accept(ExprVisitor<R> v) { return v.visitNum(this); }
}
final class Add implements Expr {
final Expr left, right;
Add(Expr l, Expr r) { left = l; right = r; }
public <R> R accept(ExprVisitor<R> v) { return v.visitAdd(this); }
}
// Mul looks the same as Add, calling v.visitMul(this)
class Evaluator implements ExprVisitor<Integer> {
public Integer visitNum(Num n) { return n.value; }
public Integer visitAdd(Add a) { return a.left.accept(this) + a.right.accept(this); }
public Integer visitMul(Mul m) { return m.left.accept(this) * m.right.accept(this); }
}
Expr e = new Add(new Num(2), new Mul(new Num(3), new Num(4)));
System.out.println(e.accept(new Evaluator())); // 14
Step throughDouble dispatch in e.accept(new Evaluator())
CallerAdd nodeEvaluatorNum and Mul nodes
accept(evaluator): first dispatch on the node type
visitAdd(this): second dispatch on the visitor type
left.accept(this), right.accept(this)
visitNum / visitMul results: 2 and 12
14

5 messages in order. Play them, or step through them one at a time.

Two virtual calls pick the code by both the node class and the operation class.

The trick is called double dispatch. Java picks an instance method by the runtime type of only one object, the receiver. When we call e.accept(visitor), the first dispatch selects Add.accept because e is really an Add. Inside it, the call v.visitAdd(this) is the second dispatch, which selects the method of whichever visitor we passed in. Two virtual calls together choose the code by both the node type and the operation type.

Notice what this buys us. A new operation, say a Printer, is one new class implementing ExprVisitor<String>, and no node class changes. But there is a catch: adding a new node type, say Neg for unary minus, means adding visitNeg to the ExprVisitor interface, and then every existing visitor must implement it. Visitor makes operations cheap and node types expensive.

3The Same Tree With Sealed Interfaces and Records

Sealed classes became a standard feature in Java 17, and Java 21 finalised pattern matching for switch and record patterns. A sealed interface lists every class allowed to implement it, so the compiler knows the complete set of node types. Records give us small immutable node classes in one line each.

Java
sealed interface Expr permits Num, Add, Mul {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
static int eval(Expr e) {
return switch (e) {
case Num(int v) -> v;
case Add(Expr l, Expr r) -> eval(l) + eval(r);
case Mul(Expr l, Expr r) -> eval(l) * eval(r);
}; // no default needed: the switch is exhaustive
}
static String print(Expr e) {
return switch (e) {
case Num(int v) -> Integer.toString(v);
case Add(Expr l, Expr r) -> "(" + print(l) + " + " + print(r) + ")";
case Mul(Expr l, Expr r) -> "(" + print(l) + " * " + print(r) + ")";
};
}
Expr e = new Add(new Num(2), new Mul(new Num(3), new Num(4)));
System.out.println(eval(e)); // 14
System.out.println(print(e)); // (2 + (3 * 4))

Several things disappeared. There is no accept() method, no visitor interface and no casts. Each operation is a plain static method, or a method on a service class, that switches over the node type. Record patterns such as Add(Expr l, Expr r) destructure the node in the case label itself, so the children are named and ready to use without calling accessors.

The important part is exhaustiveness. Because Expr is sealed, the compiler knows that Num, Add and Mul are the only possibilities, so the switch needs no default branch. If we now add record Neg(Expr operand) to the permits clause, every switch over Expr that lacks a Neg case stops compiling. That is the same safety the visitor interface gave us when we added visitNeg, but without touching any node class and without the accept() boilerplate. Notice that this only works if we avoid a default branch: a default would silently swallow the new type, so teams that rely on this safety write explicit cases.

4Comparing the Two Side by Side

The two approaches answer the same need with different trade-offs, and the table summarises them for an AST of expression nodes.

Visitor versus sealed switch for an expression AST
ConcernVisitorSealed interface + switch
New operationNew visitor class, nodes unchangedNew method with a switch, nodes unchanged
New node typeNew visit method in every visitorCompile error in every switch without a case
Boilerplateaccept() per node, visitor interfaceNone beyond the permits clause
DestructuringCall getters inside visit methodsRecord patterns in the case label
Nodes from other modulesPossible: they implement accept()Not possible: permitted types are fixed
Shared traversalBase visitor walks children onceEach switch recurses by hand
Java versionAny21 or later for pattern switch

So for a closed tree that our own team owns, built on Java 21 or later, the sealed switch is usually shorter, easier to read and just as safe. The node classes stay pure data, and each operation lives in one place where we can read it from top to bottom.

5When Visitor Is Still the Better Choice

The first case is an open hierarchy. A sealed interface must name all its subtypes, and they must live in the same module, or the same package when there are no modules. If plugins or other teams' modules are expected to add their own node types, we cannot seal the interface, and a switch over an unsealed type needs a default branch that hides missing cases. A visitor interface, by contrast, is a published contract: a plugin node implements accept() and calls a visit method, and visitors that want to handle unknown nodes can provide a generic fallback such as visitOther.

The second case is shared traversal. Real trees have dozens of node types, and most operations only care about a few of them. With a visitor we can write one base class that walks every child, like the TreeScanner class in the JDK compiler API, and each concrete visitor overrides only the two or three methods it cares about. With switches, every operation must recurse through every node type by hand, or we must build our own generic traversal helper, which is a visitor by another name.

The third case is compatibility. A library that must run on Java 11 or 17 cannot use pattern matching for switch or record patterns, so visitor remains the portable option.

6Follow-up questions

Does the sealed approach break the open-closed principle because every operation switches on type?

Not in the way older advice feared. The old warning against type switches existed because nothing checked them, so a new subtype silently fell into the wrong branch. With a sealed interface and no default branch, the compiler checks every switch, so adding a type is a guided change rather than a hidden bug. The code is open for new operations and deliberately closed for new types, which is exactly the trade-off visitor also makes.

Can we combine both approaches?

Yes. A common design keeps the nodes as records in a sealed interface for most operations and adds a small generic traversal helper, for example a method that returns the children of any node, so that operations like collecting all variable names do not need to repeat the recursion. Some teams also keep a visitor for public extension points while internal code uses switches.

7Conclusion

In this answer, we saw that visitor uses double dispatch through accept() and visit methods so that operations can be added without touching node classes, at the cost of updating every visitor when a node type is added. Sealed interfaces with records and exhaustive switches give the same compile-time safety in Java 21 with much less code, and record patterns destructure nodes in the case label. Visitor remains the better tool when the hierarchy must stay open to other modules, when many operations share one traversal, or when the code must run on older Java versions.

What to say in the interviewAbout 90 seconds aloud

Open with

Visitor solves the problem of adding operations to a fixed set of node classes. Each node has an accept method that calls the matching visit method on the visitor, so there are two dispatches, one on the node type and one on the visitor type.

Then, if they want more

That means a new operation is just a new visitor class and the nodes never change, but a new node type means adding a visit method to every visitor.

In Java 21 I can get the same safety more cheaply: I make Expr a sealed interface, the nodes become records, and each operation is a switch with record patterns like case Add(Expr l, Expr r).

Because the interface is sealed, the switch is exhaustive without a default, so adding a Neg node breaks the compile in exactly the switches that need a new case. The nodes stay plain data with no accept boilerplate. I would still choose visitor in three situations.

First, when the hierarchy has to be open, for example plugins in other modules adding node types, because sealed types must all be known in one module. Second, when many operations share a traversal, since a base visitor can walk all children once and subclasses override only the nodes they care about.

Third, for a library that must support Java versions before 21. For a closed AST my team owns on a current JDK, I would use the sealed switch.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, Java 11, Java 17
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare the visitor pattern with sealed interfaces and switch pattern matching in Java...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/741dda8a8c/