Visitor pattern
hard 55 minVisitor moves an operation on a family of classes into an object of its own.
Video lesson · Chapter 1 of 6
Make a prediction
Visitor
1:06Reel
Theory
Read or listen first. About 2 min.
What it is
Visitor is a behavioral design pattern. It represents an operation on the elements of an object structure as an object. The structure can be a list, a tree or anything that can be walked.
Each element has accept(visitor), which calls the visitor's method for that kind of element and passes itself. Two virtual calls choose the code by two types. This is called double dispatch.
The set of element types is closed, the set of operations is open.
Why it exists
Operations that do not belong to the data, such as exports, checks and reports, would otherwise fill the data classes and pull in their libraries.
An operation that is spread over many classes is hard to read and to test. In a visitor it stands in one file and may keep its own state.
Type checks with isinstance are easy to write and easy to forget. An interface with one method per type lets the language find the gap.
A short history
1986
Daniel Ingalls publishes A Simple Technique for Handling Multiple Polymorphism at OOPSLA: choosing by two types with two calls.
1994
The book Design Patterns lists Visitor among the behavioral patterns.
1998
Philip Wadler writes down the expression problem in an email of 12 November.
2014
Python 3.4 gains functools.singledispatch (PEP 443).
2017
C++17 brings std::variant and std::visit.
2023
Java 21 makes pattern matching for switch final (JEP 441), after sealed classes in Java 17 (JEP 409).
Words to know
- Visitor
- An object that holds one operation, with a method per element type.
- Element
- An object that can accept a visitor.
- Object structure
- The list or tree that holds the elements.
- Single dispatch
- The method is chosen by the type of one object, the one before the dot.
- Double dispatch
- The code is chosen by two types, here with two calls.
- Overload
- Methods with the same name and different parameter types, chosen when compiling.
- Expression problem
- Adding new types and new operations without editing code, with static safety.
- Sealed type
- A type whose subtypes are listed, so that a switch can be checked for completeness.
- Enter and leave
- Calls before and after the children of a node.
- Rewriter
- A visitor that returns a changed copy of the structure.
- Acyclic visitor
- A form with one small interface per element type.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Accept. The element's class is found
Understand it
Start here
Three callers, one street
A document has paragraphs, images and tables. Today you export it to HTML, next week to PDF, then to JSON, then someone wants a word count. The document never changes. The list of things to do with it keeps growing. The pattern on this page keeps each such thing in a class of its own.
Easy operations, hard elements. Remember the street with many callers and few building permits.
Five parts
Visitor
The interface with one method per element type:
visit_paragraph,visit_image,visit_table.Concrete visitor
One operation, complete:
HtmlExport,PdfExport,TypeChecker,Optimizer. It may collect a result.Element
The interface with
accept(visitor): a document part, a syntax node, a shape, a product.Concrete element
Paragraph,Image,Table. Itsacceptis one line: call the visitor's method for me.Object structure
The document, tree or list that leads the visitor from element to element.
Why
What goes wrong without it
There are two usual first versions. Either each class gets one method per operation, or one function asks each object for its type.
class Paragraph: def __init__(self, text): self.text = textclass Image: def __init__(self, url): self.url = urlclass Table: def __init__(self, rows): self.rows = rowsdef to_html(e): if isinstance(e, Paragraph): return f"<p>{e.text}</p>" elif isinstance(e, Image): return f'<img src="{e.url}" />' elif isinstance(e, Table): return f"<table>{len(e.rows)} rows</table>"def count_words(e): if isinstance(e, Paragraph): return len(e.text.split()) elif isinstance(e, Image): return 0 # Table was forgottendoc = [Paragraph("one two"), Image("a.png"), Table([["x"]])]print([to_html(e) for e in doc])print([count_words(e) for e in doc]) # [2, 0, None]The design that hurts
1/3Data and four jobs
Paragraph holds a text and knows four formats. To understand HTML export you must read three classes.
uses
Visitors
- A new operation is one new class
- Elements hold data only
- A missing method is reported early
- One format is one file
Methods in elements, or type checks
- A new operation edits every class
- Elements depend on export libraries
- A forgotten type is found at run time
- One format is spread over many files
The idea
Double dispatch
Which code should run depends on two types: the element and the operation. Most languages choose a method by one type, the object before the dot. Two calls in a row choose by both.
- 1
First call: element.accept(visitor)
The element's class decides which
acceptruns. After it we know: this is a paragraph. - 2
Second call: visitor.visit_paragraph(self)
The visitor's class decides which
visit_paragraphruns. After it we know: HTML, for a paragraph.
Think of two handshakes. "Hello, I am a paragraph." "Hello paragraph, I am the HTML export." Now each knows the other, and nobody asked for a type.
One document, one visitor
The pattern with a document
1/4The elements
Three kinds of parts, one method to let a visitor in.
implementsowns (dies together)depends on
The price
Operations easy, elements hard
| Change | Methods in elements | Type checks | Visitor |
|---|---|---|---|
| New operation | Edit every element | One new function | One new class |
| New element | One new class | Edit every function, easily missed | Edit every visitor, the compiler tells you |
| Elements hide their data | Yes | No | No: visitors need access |
| State during the walk | Parameters | Parameters | Fields of the visitor |
Which side grows?
A shop has 4 product types and needs tax, shipping, label and export. How do you organise it?
Breaksisinstance chains
- How
- Four functions with four branches each.
- Limit
- 16 branches, and a fifth type is missed somewhere.
- Choose when
- Throwaway scripts.
WorksMethods on products
- How
tax(),shipping(),label(),export()on each class.- Limit
- Products know tax law and file formats.
- Choose when
- Few operations, types are added often.
StrongCore in the class, the rest as visitors
- How
- Price and weight are methods. Export, label and reports are visitors.
- Limit
- Two places. The rule is: what the product is, or what somebody does with it.
- Choose when
- Operations come from several teams.
Walking
Who leads the visitor?
| Who walks | Good | Cost |
|---|---|---|
The structure: document.accept loops | Visitors need not know the shape | One fixed order |
| The elements: a section accepts for its children | Trees of any depth, see Composite | Visitor can not skip or come back |
The visitor: it calls accept on children | Full control: order, skip, results | Every visitor repeats the walk. Put it in a base visitor |
| An iterator outside | Walk and operation are separate | Nested context is lost |
A tree walked by the visitor
Choosing
When to use it and when not
Use it when
- Element types are stable, operations keep coming
- Many unrelated operations work on one structure
- Element classes should stay free of foreign libraries
- An operation must collect something over the whole structure
- Compilers: type check, optimise and generate over one syntax tree
Leave it when
- Element types are added often
- Elements must hide their state
- The structure is simple, with one or two operations
- All elements are treated the same way: a loop is enough
- Your language checks a switch over a closed set of types
What you pay
Open data
Visitors need getters. Whoever can read can also start to depend on it.
A closed list of types
Each new element breaks every visitor. With a compiler that is even a help: it shows you where.
Two jumps per element
The code path is hard to follow at first reading.
A circle of names
Elements know the visitor interface, which knows the elements. Keep them in one module.
Summary
The whole topic in one minute.
Draw the grid of types and operations. If operations grow, make each one a visitor. accept names the element's type, the visitor answers: two dispatches, no type check.
The price is fixed: each new element type touches every visitor, and elements must be readable. Decide for unknown elements whether to fail, ignore or pass on.
Return values make passes readable, immutable nodes make them safe, an explicit stack makes them survive deep input. With sealed types and a checked switch you may not need accept.
- One operation, one class. One method per element type.
- element.accept(visitor) calls visitor.visit_x(self): two dispatches, two types known.
- New operation: one class. New element: every visitor.
- accept is one line, and it has to stand in each concrete element.
- A visitor may collect state or return a value. Use a fresh one per run if it collects.
- With sealed types and a checked switch you get the same trade without accept.
Sources
- Design Patterns (publisher page)
- Philip Wadler: The Expression Problem
- Ingalls: A Simple Technique for Handling Multiple Polymorphism
- JEP 441: Pattern Matching for switch
- JEP 409: Sealed Classes
- PEP 443: Single-dispatch generic functions
- std::visit
- Python ast
- Java FileVisitor
- Java ElementVisitor
- Roslyn syntax analysis
- graphql-js visit