Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Compare a classic polymorphic composite (each node implements evaluate) with a sealed interface of records plus switch pattern matching for an expression tree in Java 21 and later. When do you choose each?

In a classic polymorphic composite, each node class implements evaluate(), so adding a node type is easy but adding an operation means editing every class. With a sealed interface of records and switch pattern matching, operations are switch expressions outside the nodes, so adding an operation is easy and the compiler checks that every node type is handled; adding a node type then causes compile errors in every switch, which shows exactly what to update. I choose sealed records when the node types are stable and there are many operations, such as evaluate, print and optimise, and polymorphism when external code must add node types.

Why this question is asked

Expression trees appear in rule engines, query builders, template languages and configuration formulas, and Java 21 made a new way of writing them practical. Interviewers ask this comparison because it is the expression problem in a concrete form: some designs make new types easy and some make new operations easy, and choosing well depends on which kind of change we expect. In this answer, we will recap both designs on the same small expression tree, add a new operation to each, add a new node type to each, look at what the compiler does for us, and then set out when to choose which.

1A Quick Recap: The Same Tree, Two Designs

Our expression tree has numbers, addition, multiplication and negation, so 2 * (3 + 4) is a Mul node whose children are Num(2) and an Add of Num(3) and Num(4). A composite, in pattern terms, is a node that contains other nodes of the same interface.

In the polymorphic design, behaviour lives in the classes: the Expr interface declares evaluate(), and each node class implements it, calling evaluate() on its children. In the data-oriented design, the nodes are plain records under a sealed interface, a Java 17 feature that lists every permitted implementation, and operations are functions that switch over the node type using pattern matching, which became final for switch in Java 21 together with record patterns.

2The Classic Polymorphic Composite

Each node knows how to evaluate itself.

Java
interface Expr { int evaluate(); }
final class Num implements Expr {
final int value; Num(int value) { this.value = value; }
public int evaluate() { return value; }
}
final class Add implements Expr {
final Expr left, right; Add(Expr l, Expr r) { left = l; right = r; }
public int evaluate() { return left.evaluate() + right.evaluate(); }
}
final class Mul implements Expr {
final Expr left, right; Mul(Expr l, Expr r) { left = l; right = r; }
public int evaluate() { return left.evaluate() * right.evaluate(); }
}
Expr e = new Mul(new Num(2), new Add(new Num(3), new Num(4)));
e.evaluate(); // 14

Adding a node type is easy and local: a new class Neg implements Expr with its own evaluate(), and no existing class changes. Other code, even in another module or library, can add node types without touching ours, because Expr is an open interface.

Adding an operation is the hard direction. If we now want print() and simplify(), we add two methods to Expr, and every node class must implement them, so one operation means editing every class. With 15 node types and 6 operations, the logic for printing is scattered over 15 files, mixed with the logic for evaluating and simplifying.

3A Sealed Interface of Records With Pattern Matching

Now the nodes are data and the operations are switch expressions.

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 evaluate(Expr e) {
return switch (e) {
case Num(int v) -> v;
case Add(Expr l, Expr r) -> evaluate(l) + evaluate(r);
case Mul(Expr l, Expr r) -> evaluate(l) * evaluate(r);
}; // exhaustive: the compiler knows these are all the cases, no default needed
}
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);
};
}
static Expr simplify(Expr e) {
return switch (e) {
case Mul(Num(int a), Expr r) when a == 1 -> simplify(r); // 1 * x -> x
case Mul(Num(int a), Expr r) when a == 0 -> new Num(0); // 0 * x -> 0
case Add(Expr l, Expr r) -> new Add(simplify(l), simplify(r));
case Mul(Expr l, Expr r) -> new Mul(simplify(l), simplify(r));
case Num n -> n;
};
}
Expr e = new Mul(new Num(2), new Add(new Num(3), new Num(4)));
evaluate(e); // 14
print(e); // 2 * (3 + 4)
simplify(new Mul(new Num(1), new Num(5))); // Num[value=5]

Adding an operation is now easy and local: print and simplify are each one new function in one place, and no record changes. Notice how simplify uses nested record patterns, Mul(Num(int a), Expr r), to match a shape of the tree several levels deep, something that would need instanceof chains and casts in the polymorphic design.

4Adding a Node Type: the Compiler Shows What to Update

Now we add negation to the sealed design: record Neg(Expr inner) implements Expr {} and Neg in the permits clause. Every switch over Expr that has no default branch stops compiling, because it is no longer exhaustive.

Java
sealed interface Expr permits Num, Add, Mul, Neg {}
record Neg(Expr inner) implements Expr {}
// javac now reports, for evaluate, print and simplify:
// error: the switch expression does not cover all possible input values
// we add the missing case in each one:
case Neg(Expr inner) -> -evaluate(inner);
Which change is easy in each design
ChangePolymorphic compositeSealed records and switch
Add a node typeEasy: one new classEdit every switch, compiler lists them
Add an operationEdit every classEasy: one new function
External code adds node typesYesNo, permits is closed
Exhaustiveness checkedOnly for interface methodsYes, for every switch without default
Match nested shapesinstanceof and castsNested record patterns

That compile error is a feature. It is a complete, precise to-do list of every operation that must learn about the new node, which in the polymorphic design we would get only for methods declared on the interface, and never for instanceof chains elsewhere in the code. The important habit is to avoid default branches in these switches, because a default silences exactly this check. The cost of the sealed design is also clear: only the module that owns Expr can add node types, since a sealed interface's permitted subclasses must be in the same module, or the same package when there is no module.

5When to Choose Each

Here is how I decide. If the set of node types is stable and known, and we expect many operations, such as evaluate, print, type-check, optimise and serialise, the sealed design wins: each operation is readable in one place, nested patterns make tree transformations short, and the compiler checks completeness. Most expression languages, rule trees and abstract syntax trees inside one application fit this description, because their grammar changes rarely while the things we do with it grow.

If external code must add node types, for example a plugin system where other teams contribute their own functions or a library whose users define custom nodes, the open polymorphic design is the right one, since a sealed hierarchy cannot be extended from outside.

The two can be combined. A sealed core with a permitted record such as Custom(String name, CustomNode impl), where CustomNode is an open interface with its own evaluate(), keeps exhaustive switches for the core while still allowing extensions at one well-defined point.

6Follow-up questions

Isn't the switch design just the visitor pattern?

It solves the same problem as the visitor pattern, adding operations without changing the node classes, but with far less code: no accept() methods, no visitor interface with one method per type, and nested patterns that visitors cannot express directly. Sealed interfaces with pattern matching are often described as the modern replacement for visitors in Java.

Why avoid a default branch?

Because a default makes the switch exhaustive no matter what, so adding a new node type no longer produces compile errors and the new type silently falls into the default. Listing every case keeps the compiler working for us.

7Conclusion

In this answer, we compared two designs for an expression tree. A polymorphic composite puts behaviour in the classes, so adding a node type is easy and adding an operation means touching every class. Sealed records with switch pattern matching put operations in switch expressions, so adding an operation is easy, the compiler checks exhaustiveness, and adding a node type produces compile errors in every switch, a precise list of what to update. We choose sealed records when node types are stable and operations are many, and polymorphism when external code must add node types.

What to say in the interviewAbout 90 seconds aloud

Open with

This is really the expression problem. In the classic polymorphic composite, each node class, Num, Add, Mul, implements evaluate and calls it on its children. Adding a node type is easy, one new class, and even other modules can do it, but adding an operation like print or simplify means adding a method to the interface and editing every class, so each operation is spread across all the node files.

Then, if they want more

With a sealed interface of records, the nodes are just data and each operation is a switch expression with record patterns, like case Add(Expr l, Expr r) returns evaluate of l plus evaluate of r. Adding an operation is one new function, and nested patterns make transformations like simplifying one times x very short.

The compiler knows the permitted types, so a switch without default is checked for exhaustiveness, and when I add a node type like Neg, every such switch fails to compile, which gives me an exact list of what to update. That's why I avoid default branches there.

So I choose sealed records when the node types are stable and I expect many operations, evaluate, print, optimise, serialise, which is typical for an expression language inside one application. I choose the open polymorphic design when external code has to add node types, like a plugin system, because a sealed hierarchy can't be extended from outside.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, 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 a classic polymorphic composite (each node implements evaluate) with a sealed...": https://scrivio-interview-library.netlify.app/java/structural-patterns/63f2c6ddfc/