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.
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.
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.
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.
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
}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.”
Elements say who they are. Visitors say what to do.
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.
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.
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).
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 BlockVisitorEvery 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.
So the two designs are mirror images.
| New element class | New operation | |
|---|---|---|
| Methods inside the classes | cheap | costly: edit every class |
| Visitor | costly: edit every visitor | cheap: 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.
ElementVisitorThe 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).
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?
accept is the hook the library calls.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.
accept method that passes itself to a visitor. Then every operation is one class,
with one visit method per element type.accept, and the visitor’s type picks visit.Checklist:
Elements say who they are. Visitors decide what to do.
Related lessons: Switch Statements, Polymorphism, Dynamic Dispatch, Encapsulation, Composite, Iterator.
ElementVisitor and
Element.accept javadoc.