Notes
The problem
Here is the first attempt. A postage method takes any item and runs a chain of instance of checks. It works for letters and boxes. But someone forgot the chilled box, so it silently costs zero. Now copy this chain for labels, for customs and for reports. Each copy can miss a type, and nothing warns you. The bug only shows up when a customer ships ice cream for free.
The other option is to put each operation inside the classes: a postage method, a label method and a customs method on all three. Now the type checks are gone, but the shipment classes keep growing with code that is not really theirs. Printing and tax rules sit next to the data. Every new report means editing, retesting and redeploying all three classes. Neither option scales.
long postage(Object item) {
if (item instanceof LetterItem l)
return 500 + (l.express() ? 300 : 0);
else if (item instanceof BoxItem b)
return 4000 + b.grams() / 100 * 50;
return 0; // ColdBox forgotten!
} The idea
The idea in one sentence: move each operation out of the element classes and into its own visitor class, which has one visit method per element type. The elements learn just one small trick, an accept method that hands themselves to the visitor. Formally, Visitor represents an operation over a group of related types, so you can add new operations without changing those types.
- move each operation out of
- the classes, into a visitor
- class with one visit method
- per element type
- elements only learn one
- trick: accept(visitor)
Structure
Here is the full picture. On the left, the Shipment interface and its three element classes. On the right, the ShipmentVisitor interface and the operations: PostageCalculator, LabelPrinter, and later CustomsCheck. The Dispatcher holds a list of shipments and a visitor, and simply asks each shipment to accept the visitor. It never checks types itself.
Code: elements
The element side is tiny. The Shipment interface has a single generic accept method that takes a visitor and returns whatever that visitor produces. Each element implements it in one line: the box calls visit box and passes itself. The letter calls visit letter, the cold box calls visit cold box. The elements stay as plain data records. They do not know what postage or labels are.
interface Shipment {
<R> R accept(ShipmentVisitor<R> v);
}
record BoxItem(String id, int grams)
implements Shipment {
public <R> R accept(
ShipmentVisitor<R> v) {
return v.visitBox(this);
}
} Code: visitor
The visitor interface lists one visit method for every element type. Making it generic is a neat Java touch: the postage calculator returns a Long number of cents, and the label printer returns a String. No casting, no shared result field. If you prefer, visitors can also keep state, like a running total, and return nothing.
interface ShipmentVisitor<R> {
R visitLetter(LetterItem letter);
R visitBox(BoxItem box);
R visitColdBox(ColdBox box);
}
PostageCalculator
implements ShipmentVisitor<Long>
LabelPrinter
implements ShipmentVisitor<String> Code: one operation
Now every postage rule lives in one class. Letters cost five hundred cents plus a fee for express. Boxes pay by weight. Chilled boxes pay by weight plus a charge for each hour of cooling. If the pricing team changes a rate, you open exactly one file. And because the interface demands a visit cold box method, you cannot forget the chilled box: the code will not compile.
public Long visitLetter(LetterItem l) {
return 500L + (l.express() ? 300 : 0);
}
public Long visitBox(BoxItem b) {
return 4000L + b.grams() / 100 * 50L;
}
public Long visitColdBox(ColdBox c) {
return 6000L + c.grams() / 100 * 80L
+ c.hoursCold() * 100L;
} Double dispatch
Watch one call. The dispatcher holds the box only as a Shipment, so it calls accept with the postage visitor. Java picks the box's accept at runtime. That is the first dispatch. Inside, the box calls visit box on the visitor, and Java picks the postage version at runtime. That is the second dispatch. Two virtual calls together choose the code by both the element type and the operation. This is called double dispatch.
Why the extra hop? Java chooses between overloaded methods by the declared type, at compile time, not by the real object. If a variable is declared as Shipment, the compiler cannot pick visit box for it. Calling accept on the object first lets normal runtime dispatch find the real class, and inside that class this has the exact type. That one line is the whole trick.
- visit(LetterItem) and
- visit(BoxItem) as overloads
- are picked by the STATIC
- type at compile time
- Shipment s = new BoxItem(..)
- visit(s) finds no match
- accept() turns the static
- type into the real type
Adding an operation
Here is the payoff. The customs team wants to know which shipments need a declaration. Letters never do, boxes over two kilograms do, chilled food always does. You write a CustomsCheck class that implements the visitor and returns a Boolean. You do not touch LetterItem, BoxItem or ColdBox. Tested classes stay closed, and the new rule is reviewed on its own.
The trade-off
The cost is on the other side. If the business adds a fourth type, say a drone parcel, the visitor interface gets a new method and every visitor must implement it. The compiler will list every place you need to change, which is helpful, but it is still many files. So the rule is simple: use Visitor when the set of types is stable and the list of operations keeps growing. If it is the opposite, plain polymorphism is better.
- new operation:
- one new visitor class
- new element type:
- new visit method in the
- interface and in EVERY
- visitor
- pick Visitor when types are
- stable and operations grow
When to use it
Use Visitor when the element types are stable, there are many unrelated operations, and you often walk a mixed list or a tree of them. Skip it when new types arrive often, when there is only one operation, which a normal method handles fine, or when visitors would need private fields the elements should keep hidden. Visitor also feels heavy to newcomers, so do not reach for it for two classes.
- use it when:
- • types are stable
- • many unrelated operations
- • you walk a tree or list of
- mixed objects
- skip it when:
- • new types arrive often
- • there is only one operation
- • elements must hide fields
Modern Java
Modern Java offers another route. In Java seventeen you can declare Shipment as a sealed interface that permits only the three record types. From Java twenty one, a switch with type patterns over a sealed type is checked for exhaustiveness, so a missing case fails to compile, with no accept methods at all. Many teams now prefer that for data records. On Java seventeen, the classic visitor is still the safe way to get that check.
- Java 17: sealed interface
- Shipment permits LetterItem,
- BoxItem, ColdBox
- Java 21: a switch with type
- patterns over a sealed type
- is checked for missing
- cases, with no accept()
- same goal: no forgotten type
Where you see it
You have used visitors already. The Java annotation processing API has an Element interface with an accept method that takes an ElementVisitor, exactly this pattern. Files dot walk file tree calls a FileVisitor for each folder and file, a looser callback style of the same idea. And almost every compiler, linter and code formatter walks its syntax tree with visitors.
- javax.lang.model:
- Element.accept(ElementVisitor)
- used by annotation processors
- java.nio.file.FileVisitor:
- callbacks per file and
- folder in Files.walkFileTree
- compilers and linters walk
- syntax trees with visitors
Related patterns
Do not confuse it with Strategy. A strategy is one swappable algorithm for one context. A visitor is one operation spread across many element types. Visitor pairs naturally with Composite: the composite builds a tree, like folders and files, and visitors compute size or search it. And compared with Iterator, the iterator decides how you move through items, while the visitor decides what you do at each one.
- Strategy: one interchangeable
- algorithm for one context
- Visitor: one operation spread
- over MANY element types
- Composite: the tree that a
- visitor often walks
- Iterator: how you move;
- Visitor: what you do
In LLD interviews
In interviews, Visitor fits when a stable hierarchy needs many calculations. A file system design where you compute total size, search and permissions over files and folders. A cart where tax rules differ by item type. An expression tree you evaluate, print and simplify. The common mistake is using it on a hierarchy that changes every sprint. Say the trade-off out loud and the interviewer will trust the choice.
- file system: size, search,
- permissions over files
- and folders
- shopping cart: tax and
- discount per item type
- expression tree: evaluate,
- print, simplify
- mistake: Visitor for a
- hierarchy that keeps growing