Quick revision
The short answer
Replacing a Visitor with sealed interfaces and pattern switches removes the accept and visit boilerplate, puts each operation in one readable method, and gives compile-time exhaustiveness. What we lose is the open extension a Visitor allows across modules, and adding a node type now means updating every switch, though the compiler finds them all. We decide per module: closed node sets with frequently added operations suit switches, while hierarchies that other modules extend keep the Visitor.
What to remember
In this answer, we compared the Visitor pattern with sealed interfaces and pattern switches over an AST. The switch version removes accept methods and visitor classes, keeps each operation in one method and checks exhaustiveness at compile time. It gives up the ability for other modules to add node types, and every new node type forces every switch to be updated, which the compiler finds for us. We choose per module based on who adds node types and how often operations change, and we migrate one operation at a time with output comparisons.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Replacing a Visitor with sealed interfaces and pattern switches removes the accept and visit boilerplate, puts each operation in one readable method, and gives compile-time exhaustiveness. What we lose is the open extension a Visitor allows across modules, and adding a node type now means updating every switch, though the compiler finds them all. We decide per module: closed node sets with frequently added operations suit switches, while hierarchies that other modules extend keep the Visitor.
Why this question is asked
An AST, an abstract syntax tree, is the tree of nodes a parser builds from code or an expression, and almost every compiler, query engine or rules engine has one. For decades the Visitor pattern was how Java code ran operations over such trees. Java 21 gave us a simpler tool, and teams are now deciding whether to move. Interviewers ask this because it tests whether we can weigh a language feature against a well-known design pattern instead of treating the newer option as automatically better. In this answer, we will recap what the Visitor gives us, show the same operation both ways, list what changes on each side, explain how to decide per module, and describe a safe migration.
1A Quick Recap of the Visitor Pattern
Java picks which method to run based on the run-time type of the receiver, the object before the dot, but not on the run-time type of the arguments. If we have a variable of type Node and call print(node), overloads for Num and Add are chosen at compile time from the declared type Node, which is not what we want.
The Visitor works around this with double dispatch. Each node class has an accept(Visitor v) method that calls v.visitNum(this) or v.visitAdd(this). The first dispatch picks the node's accept method, and the second picks the right visit method. Every operation, such as evaluating or printing, becomes a class implementing the Visitor interface. It works, but every node needs accept, every operation needs a class, and the logic for one operation is spread across visit methods that read like a list of callbacks.
2The Same Evaluator Written Both Ways
Here is a tiny expression tree evaluated first with a Visitor and then with a sealed interface and a switch. A sealed interface lists the only classes allowed to implement it, using permits, so the compiler knows the complete set of node types.
Notice that the sealed version has no accept methods and no Visitor interface. The evaluator is one method we can read from top to bottom, and record patterns pull the fields out directly. If we add a node type Times to the permits clause, eval stops compiling until we add a case for it, which is the exhaustiveness check doing the job the Visitor interface used to do.
3What We Gain and What We Lose
The gains are real. There is much less code, each operation lives in one place, and adding a new operation is just writing a new method with a switch; no node class changes. Exhaustiveness checking means a missing case is a compile error rather than a forgotten visit method.
The losses are about extension. With a Visitor, double dispatch is part of the design, so code outside the module can work with the hierarchy through a stable interface. With a sealed interface, the set of node types is closed: only the classes in permits can exist, and they must be in the same module (or the same package, in the unnamed module). Adding a node type means touching every switch over the hierarchy. The compiler finds each one, which is a big help, but in a large codebase that can be dozens of files changed at once. The Visitor has the same cost, since a new visit method breaks every visitor, but a Visitor with default methods can soften it, while a switch has no such escape hatch other than a default branch, which gives up exhaustiveness.
| Concern | Visitor | Sealed + switch |
|---|---|---|
| Boilerplate | accept on every node, one class per operation | none beyond the records |
| Reading one operation | spread across visit methods | one method, top to bottom |
| Adding an operation | new visitor class | new method with a switch |
| Adding a node type | new visit method breaks every visitor | every switch fails to compile until updated |
| Node types from other modules | possible with an open interface | not possible: the set is closed |
| Missing case detection | compile error on the interface | compile error from exhaustiveness |
4Deciding Module by Module
This trade-off is old and has a name, the expression problem: some designs make it easy to add operations, others make it easy to add types, and few do both. So the question for each module is which kind of change happens more often, and who makes it.
Pattern switches fit when the node types are closed and owned by one team, and new operations arrive often. A SQL parser's AST is a good example: the grammar changes a few times a year, but new analyses, rewrites and printers are added every sprint. The Visitor still fits when other modules or plugins must define their own node types, because a sealed hierarchy cannot admit them. A rules engine where customers register custom condition nodes is a case where we would keep it.
There is also a middle path. A module can expose a sealed core hierarchy for its own operations and keep a small Visitor-style extension interface for the one place where outsiders plug in. We decide per module rather than per codebase because the answer really differs between, say, the parser and the plugin API.
- Do other modules need to add node types?YesKeep the Visitor or an open interfaceNoContinue
- Are new operations added more often than node types?YesUse sealed types and switchesNoEither works; prefer the simpler code
- Migrate with output tests in placecompare old and new results per operation
3 steps in order. Play them, or step through them one at a time.
5Migrating Incrementally
We do not need a big-bang rewrite. The node classes can implement the sealed interface and keep their accept methods for a while, so both styles work at once. We then convert one operation at a time, starting with the simplest, and before switching any caller we run the old visitor and the new switch on the same set of trees and compare outputs. A corpus of a few thousand real inputs, such as saved queries, makes this check strong. When the last visitor is gone, we delete the accept methods and the Visitor interface in one final change. This keeps every step small and reversible, and it means a mistake in one converted operation never blocks the rest.
6Follow-up questions
Is a pattern switch slower than a Visitor's virtual calls?
Usually not in a way that matters. A pattern switch compiles to an invokedynamic call backed by SwitchBootstraps, which the JIT optimizes well, while the Visitor does two virtual calls per node. For hot code we would measure both with JMH on real trees rather than guess.
Can we keep exhaustiveness and still allow a fallback?
Not in the same switch. Adding a default branch makes the switch compile when a new node type appears, which removes the compile error we wanted. If a fallback is truly needed, it is better to make that decision visible, for example a sealed subtype Unknown that carries unparsed data and is handled explicitly.
What happens if a node type is added in a separately compiled module?
Within one module the compiler checks everything, but if a switch was compiled against an older permits list and meets a new subtype at run time, the synthetic default that the compiler inserted throws MatchException. Rebuilding modules together avoids this.
7Conclusion
In this answer, we compared the Visitor pattern with sealed interfaces and pattern switches over an AST. The switch version removes accept methods and visitor classes, keeps each operation in one method and checks exhaustiveness at compile time. It gives up the ability for other modules to add node types, and every new node type forces every switch to be updated, which the compiler finds for us. We choose per module based on who adds node types and how often operations change, and we migrate one operation at a time with output comparisons.
Open with
I would treat it as a per-module decision based on the expression problem. With sealed interfaces, records and pattern switches, we get rid of accept methods and visitor classes, each operation becomes one readable method, and because the hierarchy is sealed the compiler checks exhaustiveness, so a missing case is a compile error.
Then, if they want more
What we lose is double dispatch as an extension point. A sealed hierarchy is closed, so other modules or plugins cannot add node types, and when we add a node type ourselves every switch over it has to change. The compiler finds all of them, but in a big codebase that is a wide change.
So my rule is: if the node types are closed and owned by one team and we add operations often, like a parser AST where new analyses come every sprint, switch to sealed types. If outside modules need to define node types, keep the Visitor or an open interface there, maybe with a sealed core inside.
For the migration, I would make the nodes implement the sealed interface while keeping accept, convert one visitor at a time, run old and new versions on the same corpus of real trees and compare outputs, and only delete the Visitor interface when the last one is converted.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "Your team is replacing a Visitor pattern over an AST with sealed interfaces and pattern...": https://scrivio-interview-library.netlify.app/java/sealed-and-pattern-matching/d6e57adebd/