Visitor

November 26, 202611 minutes

A page editor's three block classes keep gaining operations. Learn how double dispatch lets one accept method serve any number of visitors, what it costs, and when a sealed interface and a pattern switch is the better answer.

Your page editor has three kinds of block: headings, paragraphs and images. Each one knows how to turn itself into HTML. Then the requests arrive. Export to markdown. A word count. A check that every image has alt text. Every request means opening all three classes again, and the image class slowly learns about HTML, markdown and screen readers. Worse, a partner team wants a PDF export, and can’t edit your classes. How do you add an operation without opening every class? There’s a pattern for exactly this, and it’s called Visitor.

Prefer to watch? The narrated video covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.

Four requests, three classes

Every new operation is a new method in every class. Four operations in three classes is twelve methods, and the partner team’s PDF export has nowhere to go.

Grid of three block classes (Heading, Paragraph, Image) by four operations (toHtml, toMarkdown, wordCount, checkAltText); every cell is a method that must be written, and a partner team's PDF export cannot reach the classes. Grid of three block classes (Heading, Paragraph, Image) by four operations (toHtml, toMarkdown, wordCount, checkAltText); every cell is a method that must be written, and a partner team's PDF export cannot reach the classes.
Three classes, four operations, twelve methods.

The inspector’s binder

Think of a home inspector. A house has different kinds of rooms: a kitchen, a bathroom, a garage. The inspector carries a binder with one page for each kind. At each room, the inspector asks one question: who are you? The room answers, I’m a kitchen. And the inspector turns to the kitchen page.

An electrician brings a different binder, a fire inspector another. The rooms never change. A new inspector is just a new binder. But build a sauna, and every binder needs a new page. That’s the price.

In code, the rooms are the elements. The inspector is the visitor. And each page in the binder is a visit method.

Mapping: rooms (kitchen, bathroom, garage) are elements; an inspector with a binder is a visitor; each page of the binder is a visit method; a new inspector is a new visitor; a new kind of room means a new page in every binder. Mapping: rooms (kitchen, bathroom, garage) are elements; an inspector with a binder is a visitor; each page of the binder is a visit method; a new inspector is a new visitor; a new kind of room means a new page in every binder.
The analogy, mapped.

The obvious version: one method per operation

Here’s the obvious design. The Block interface has one method, toHtml, and each block class implements it.

public interface Block {
    String toHtml();
}

public record Heading(int level, String text) implements Block {
    public String toHtml() { return "<h" + level + ">" + text + "</h" + level + ">"; }
}

public record Paragraph(String text) implements Block {
    public String toHtml() { return "<p>" + text + "</p>"; }
}

public record Image(String url, String alt) implements Block {
    public String toHtml() { return "<img src=\"" + url + "\" alt=\"" + alt + "\">"; }
}

With one operation, that’s a good design. The code for a heading lives in the heading. There’s nothing clever to explain. It’s polymorphism at work: call toHtml on any block, and Java picks the right class at run time (see Dynamic Dispatch). HTML escaping is left out to keep the example short.

Why it breaks

Add markdown. Then a word count. Then the alt text check. Each one is a new method in every block class. Four operations in three classes is twelve methods. The image class now knows HTML, markdown, counting and accessibility, and none of that is about images. And the partner team’s PDF export has nowhere to go: it’s their operation, and they don’t own your classes.

So move the operations out, into a renderer class with one method per block type. Then loop over the page and render each block.

class HtmlRenderer {
    String render(Heading h)   { /* ... */ }
    String render(Paragraph p) { /* ... */ }
    String render(Image i)     { /* ... */ }
}

for (Block block : page) {
    html.render(block);   // compile error: render(Block) doesn't exist
}

It won’t compile. The variable is typed Block, so Java looks for render(Block). It doesn’t look at what the block actually holds. Overloads are chosen by the declared type (JLS §15.12.2).

The other way out is a chain of instanceof checks. That compiles. But add a new kind of block, and it falls to the last line, and nothing warns you.

String render(Block block) {
    if (block instanceof Heading h)   return /* ... */;
    if (block instanceof Paragraph p) return /* ... */;
    if (block instanceof Image i)     return /* ... */;
    return "";   // a new kind of block lands here, unnoticed
}

The key idea: ask twice

Java picks an overload by the type the compiler can see. It picks an overridden method by the object’s real type, at run time (JLS §15.12.4). So let the block make the call. A block always knows what it is. Inside the Heading class, this is a Heading, for certain.

public record Heading(int level, String text) implements Block {
    public <R> R accept(BlockVisitor<R> visitor) { return visitor.visit(this); }
}

Hand the block a visitor. The block calls visit and passes itself. Now the compiler sees a Heading, and picks the visit(Heading) overload.

That’s two dispatches. First, the block’s own type decides which accept runs. Second, the visitor’s type decides which visit runs. The Gang of Four call accept a double-dispatch operation: “Its meaning depends on two types: the Visitor’s and the Element’s.” Their intent for the pattern (Design Patterns, 1994): “Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.”

Sequence: the client calls accept on a Heading block, passing an HtmlRenderer; the Heading calls visit with itself on the visitor; the HtmlRenderer's visit(Heading) overload runs and returns the HTML. Sequence: the client calls accept on a Heading block, passing an HtmlRenderer; the Heading calls visit with itself on the visitor; the HtmlRenderer's visit(Heading) overload runs and returns the HTML.
Ask twice: first the block, then the visitor.

Elements say who they are. Visitors say what to do.

Building it

Here’s the visitor interface: one visit method for each kind of block. The Block interface shrinks to one method, accept.

public interface BlockVisitor<R> {
    R visit(Heading heading);
    R visit(Paragraph paragraph);
    R visit(Image image);
}

public interface Block {
    <R> R accept(BlockVisitor<R> visitor);
}

Each block class implements accept the same way: call visit, and pass this. One line each, written once, never again.

public record Heading(int level, String text) implements Block {
    public <R> R accept(BlockVisitor<R> visitor) { return visitor.visit(this); }
}

public record Paragraph(String text) implements Block {
    public <R> R accept(BlockVisitor<R> visitor) { return visitor.visit(this); }
}

public record Image(String url, String alt) implements Block {
    public <R> R accept(BlockVisitor<R> visitor) { return visitor.visit(this); }
}

Now an operation. The HTML renderer implements the visitor and returns a string. One method per block type, all in one place.

public class HtmlRenderer implements BlockVisitor<String> {
    public String visit(Heading h) { return "<h" + h.level() + ">" + h.text() + "</h" + h.level() + ">"; }
    public String visit(Paragraph p) { return "<p>" + p.text() + "</p>"; }
    public String visit(Image i) { return "<img src=\"" + i.url() + "\" alt=\"" + i.alt() + "\">"; }
}

Follow an image through. The loop calls accept on the block. The image’s accept runs, and calls visit with itself. The renderer’s image method produces the tag.

BlockVisitor<String> html = new HtmlRenderer();
for (Block block : page) {
    out.append(block.accept(html)).append('\n');
}

A second operation is a second class. The word counter answers with a number, and images count as zero.

public class WordCounter implements BlockVisitor<Integer> {
    public Integer visit(Heading h) { return words(h.text()); }
    public Integer visit(Paragraph p) { return words(p.text()); }
    public Integer visit(Image i) { return 0; }

    private int words(String text) { return text.isBlank() ? 0 : text.trim().split("\\s+").length; }
}

A visitor can also remember things. The alt text auditor keeps a list of problems, and fills it while it visits.

public class AltTextAuditor implements BlockVisitor<Void> {
    private final List<String> problems = new ArrayList<>();

    public Void visit(Heading h) { return null; }
    public Void visit(Paragraph p) { return null; }
    public Void visit(Image i) {
        if (i.alt().isBlank()) problems.add("missing alt text: " + i.url());
        return null;
    }

    public List<String> problems() { return problems; }
}

And the partner team’s PDF export? It’s just their own visitor, in their own code. Your classes never changed.

Anatomy and design choices

The pattern has four parts. First, the element interface, here Block. Second, the concrete elements: Heading, Paragraph and Image. Third, the visitor interface. And fourth, the concrete visitors.

Class diagram: Heading, Paragraph and Image implement the Block interface, which has accept(visitor); HtmlRenderer, WordCounter and AltTextAuditor implement the BlockVisitor interface, which has a visit method for each block type; Block uses BlockVisitor. Class diagram: Heading, Paragraph and Image implement the Block interface, which has accept(visitor); HtmlRenderer, WordCounter and AltTextAuditor implement the BlockVisitor interface, which has a visit method for each block type; Block uses BlockVisitor.
Four parts.

Who walks through the page? Not the visitor. A plain loop does. For a tree, each accept would hand the visitor on to its children (the Gang of Four allow the structure, the visitor or an iterator to do the walking). That is why a visitor often travels over a composite. The visitor decides what to do at each stop.

One more cost: a visitor only sees what an element exposes. Our records expose their fields, so that works. Anything private stays out of reach, unless you open it up, which weakens encapsulation.

And the type parameter is what each visitor answers with: a string (HtmlRenderer), a number (WordCounter), or nothing at all (AltTextAuditor, which Java spells Void).

The price: a new element breaks every visitor

Now the sauna. Add a table block, and the visitor interface needs a new method.

public record Table(List<List<String>> rows) implements Block {
    public <R> R accept(BlockVisitor<R> visitor) { return visitor.visit(this); }
}

// BlockVisitor<R> gains:  R visit(Table table);
// HtmlRenderer: is not abstract and does not override abstract method visit(Table) in BlockVisitor

Every visitor stops compiling until it learns about tables. That’s loud, which is good. But with twenty visitors, it’s twenty edits. The Gang of Four put it plainly: adding new ConcreteElement classes is hard.

Adding a Table block adds visit(Table) to BlockVisitor; HtmlRenderer, WordCounter, AltTextAuditor and every other visitor fail to compile until each one gets a visit(Table) method. Adding a Table block adds visit(Table) to BlockVisitor; HtmlRenderer, WordCounter, AltTextAuditor and every other visitor fail to compile until each one gets a visit(Table) method.
One new block, every visitor changes.

So the two designs are mirror images.

New element classNew operation
Methods inside the classescheapcostly: edit every class
Visitorcostly: edit every visitorcheap: one new class

Ask which one changes more often: the kinds of block, or the things you do with blocks? That’s the whole decision.

In the JDK: ElementVisitor

The JDK has a famous one. Java’s compiler API models source code as elements: packages, types, executables and variables. Every Element has an accept(ElementVisitor<R,P>, P) method, and ElementVisitor has one visit method per kind of element. It’s our pattern with a different cast. The javadoc describes it as “a visitor of program elements, in the style of the visitor design pattern.”

Element element = /* handed over by the compiler */;
String kind = element.accept(new SimpleElementVisitor14<String, Void>("other") {
    @Override public String visitType(TypeElement e, Void p)             { return "type"; }
    @Override public String visitExecutable(ExecutableElement e, Void p) { return "executable"; }
    @Override public String visitVariable(VariableElement e, Void p)     { return "variable"; }
}, null);

Here a small visitor labels any element. The compiler can’t know the kind, so the element chooses.

And there’s the price. When the language adds a new kind of element, a visitor may be handed one it has never seen. So the interface has visitUnknown, just for that: “This can occur if the language evolves and new kinds of elements are added to the Element hierarchy.” The javadoc also warns that classes implementing the interface directly can become source-incompatible with future releases, and recommends extending the ready-made visitor classes in javax.lang.model.util instead (SimpleElementVisitor14 above is one of them).

Today’s alternative: sealed types and a pattern switch

Modern Java has a second answer. Seal the Block interface (Java 17), so the compiler knows every block type. Then write each operation as a switch (Java 21).

public sealed interface Block permits Heading, Paragraph, Image {}

public record Heading(int level, String text) implements Block {}
public record Paragraph(String text) implements Block {}
public record Image(String url, String alt) implements Block {}

Each operation becomes one method with a pattern switch. No accept, and no visitor interface. And if you leave out a case, the compiler tells you: a switch expression must be exhaustive (JEP 441).

static int wordCount(Block block) {
    return switch (block) {
        case Heading h   -> words(h.text());
        case Paragraph p -> words(p.text());
        case Image i     -> 0;
    };
}

static int words(String text) { return text.isBlank() ? 0 : text.trim().split("\\s+").length; }

Add a table, and every switch without a case for it stops compiling. It’s the same price, with less ceremony. Our Switch Statements lesson covers pattern switches in depth.

When is a visitor still the better pick?

  • When the elements aren’t sealed, like the compiler API, where anyone’s code can implement the element interfaces.
  • When your Java has no pattern switches: sealed types arrived in Java 17 and pattern switches in Java 21.
  • When a library has to call your operation, because accept is the hook the library calls.
Decision: do you own a sealed hierarchy on Java 21 or later? Then use a pattern switch. Is the element set open, is your Java older, or must a library call your operation? Then use a visitor. Do you have only one or two operations? Put the methods in the classes. Decision: do you own a sealed hierarchy on Java 21 or later? Then use a pattern switch. Is the element set open, is your Java older, or must a library call your operation? Then use a visitor. Do you have only one or two operations? Put the methods in the classes.
Which side of the trade changes less?

When not to use it

When should you skip it? With one or two operations, put the methods inside the classes. That’s the obvious version, and it’s fine. If new kinds of element keep arriving, a visitor will hurt: every new type touches every visitor. If you own a sealed hierarchy, a pattern switch does the same job in less code. And if the operation is the element’s own business, like an order working out its own total, keep it inside. Visitors are for operations that belong to someone else.

Recap

  • When you keep adding operations to a stable family of classes, don’t open every class each time.
  • Give each element one accept method that passes itself to a visitor. Then every operation is one class, with one visit method per element type.
  • That’s double dispatch: the element’s type picks accept, and the visitor’s type picks visit.
  • A new operation is easy. A new element type touches every visitor.
  • Sealed types with a pattern switch strike the same bargain, with less code.
Recap chain: stable classes with growing operations, one accept per element, one visitor per operation, new operation easy and new element costly. Recap chain: stable classes with growing operations, one accept per element, one visitor per operation, new operation easy and new element costly.
Elements say who they are. Visitors decide what to do.

Checklist:

  • Do you have a stable family of classes and a growing list of operations on them?
  • Can the operations be written without the elements’ private details (or are you willing to expose them)?
  • Does the element set change rarely? (If not, every new type will touch every visitor.)
  • Is the hierarchy open, or on older Java? (Otherwise a sealed interface and a pattern switch is simpler.)
  • Is the operation really someone else’s job, and not the element’s own business?

Elements say who they are. Visitors decide what to do.

Related lessons: Switch Statements, Polymorphism, Dynamic Dispatch, Encapsulation, Composite, Iterator.

Further reading