Video in progress

Strong Middle 🧭 Design patterns

Now that Java 21 has sealed interfaces and `switch` pattern matching, do we still need the Visitor pattern?

In most cases no: a switch over a sealed hierarchy does what Visitor does, a separate operation per type plus compiler-checked exhaustiveness, with less code. Visitor is still the right choice when the hierarchy can't be changed, such as in a library, or when the traversal logic is complex.

📖 Answer

The point of Visitor is to add new operations to a class hierarchy without touching it. The price was high: an accept(Visitor v) in every class, a visitX method in the interface for each type, and double dispatch.

In Java 21 the same thing looks like this:

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 n -> n.value();
        case Add(Expr l, Expr r) -> eval(l) + eval(r);
        case Mul(Expr l, Expr r) -> eval(l) * eval(r);
    };
}

There is no default. If a new Div type is added, every switch written without default stops compiling. That is the same safety you get when you add a method to a Visitor interface, but without the accept methods. Record patterns (Add(Expr l, Expr r)) also unpack the inner values.

When Visitor stays:

  • the hierarchy lives in another module or library and can't be made sealed;
  • the traversal logic is complex and reused: ASM's ClassVisitor, or FileVisitor in Files.walkFileTree. Here a visitor is more than a pick-by-type: it has enter and exit hooks too;
  • the team still runs something older than Java 17.

One trap: if you add a default to the switch, the compiler stops checking exhaustiveness, and a new type silently falls into default. Make it a habit not to write default on sealed types.