Programming Search⌘K

Patterncore

Visitor pattern

Also called Visitor, double dispatch, tree walker.

An operation on an object structure becomes a separate object with one method for each kind of element. Operations are then cheap to add, and kinds of element are expensive to add.

Family
behavioral-design
Intent
Represent an operation to be performed on the elements of an object structure, so that an operation can be added without a change to the classes of the elements.
Refactorings
Move accumulation to visitor

Intent

Represent an operation on the elements of an object structure as an object. A program can then add an operation and not change the classes of the elements.1 Each visitor holds one operation, with one method for each kind of element.

Problem

A compiler holds a program as an abstract syntax tree. The tree has a class for each kind of node: assignments, variable references, arithmetic expressions. The compiler needs many operations on the tree: type checking, code generation, pretty printing, metrics. Design Patterns starts from this example.1

The first design puts each operation in the node classes as a method. Then each node class has a method for type checking, a method for code generation, and a method for each other operation. The code for one operation is spread over all the classes. To add an operation, a programmer must change every node class. And the node classes mix unrelated concerns.

The forces are these. The node classes rarely change. The operations change often, and each operation should be in one place. And an operation must run different code for each kind of node, without a chain of type tests.

Solution

Design Patterns names five participants.1

  • Visitor declares a visit operation for each class of ConcreteElement.
  • ConcreteVisitor implements each visit operation. It is one operation of the program, and it can keep state while it runs.
  • Element declares an accept operation that takes a visitor.
  • ConcreteElement implements accept by calling the visit operation for its own class.
  • ObjectStructure holds the elements and can let a visitor visit each of them.

Double dispatch

A call such as node.op() picks the method by one class, the class of node. The Visitor pattern needs the code to depend on two classes: the kind of node and the operation. It gets this with two calls. node.accept(visitor) picks a method by the class of the node. That method calls visitor.visitAdd(this), which picks a method by the class of the visitor. Design Patterns calls this double dispatch.1 The JavaScript and the first Java example use it.

The expression problem

The examples hold the expression (2 + 3) * 4 as a tree of Num, Add and Mul nodes. They run three operations: show, evaluate and count. Think of the program as a table. Each kind of node is a row, and each operation is a column. Norvig draws this matrix of types and operations.3

Change Methods in the node classes Visitors, or a sum type and a match
Add an operation change every class add one visitor or one function
Add a kind of node add one class change every visitor or function

Wadler named this the expression problem. The goal is to define a data type by cases, and then add cases and add functions without recompiling the existing code and without casts. In his words, cases are rows and functions are columns. In a functional language, the rows are fixed, and a column can be added without a change to the existing code. In an object-oriented language, the columns are fixed, and a row can be added in the same way.2 The Visitor pattern moves an object-oriented program to the functional side of the table. Design Patterns says the same: with visitors, an operation is cheap to add and an element class is expensive to add.1 Neither design makes both changes cheap. Wadler cites earlier work by Reynolds (1975), Cook (1990), and Krishnamurthi, Felleisen and Friedman (1998), and his own solution in GJ uses a Visitor interface.2

Sum types and pattern matching

A language with sum types and pattern matching has the functional side of the table as a built-in form. A sum type, such as a Rust enum or a Java sealed interface with records, lists every kind of node. A match on it is an operation with a case for each kind. No accept method and no visitor interface are needed.

The compiler can check that a match covers every case. A Rust match must cover every variant.8 A Java switch over a sealed type with no default must cover each permitted subtype.67 TypeScript checks a discriminated union when the default case assigns the value to a variable of type never.9 C++ std::visit does not compile when an alternative of the std::variant has no overload.10 With these checks, a kind of node added to the type turns each operation that lacks it into a compile error. The classic Visitor gives the same check, because each visitor class must implement every method of the interface.

In Python, a match statement runs, but nothing checks it before it runs. This program adds Neg to the type and forgets to add a case to show:

This code runs but gives a wrong answer on purpose.

from dataclasses import dataclass


@dataclass
class Num:
    value: int


@dataclass
class Neg:
    operand: "Expr"


type Expr = Num | Neg


def show(e: Expr) -> str:
    match e:
        case Num(value):
            return str(value)


print("show:", show(Neg(Num(2))))
Output
show: None

No case matches, so the match does nothing, and the function returns None. The program prints a wrong result and does not stop. The fix is a last case that calls typing.assert_never. A static type checker reports an error when it finds that the call can be reached. At run time the call raises an exception.5

This code raises AssertionError, on purpose.

from dataclasses import dataclass
from typing import assert_never


@dataclass
class Num:
    value: int


@dataclass
class Neg:
    operand: "Expr"


type Expr = Num | Neg


def show(e: Expr) -> str:
    match e:
        case Num(value):
            return str(value)
        case _:
            assert_never(e)


print("show:", show(Neg(Num(2))))

Who traverses the structure

Design Patterns gives three places for the traversal: the object structure, the visitor, or a separate iterator.1 In the examples, most operations recurse on their own. The TypeScript example puts the traversal in one fold function, and each visitor receives the results of the children. Go's ast.Walk holds the traversal, and Visit returns the visitor to use for the children, or nil to skip them.12 Python's ast.NodeVisitor has generic_visit, which visits the children of a node.4

Example

Language Form
Python dataclasses and match; a second program with ast.NodeVisitor
JavaScript classes with accept, and visitors as objects of functions
TypeScript a discriminated union, a fold, and visitors as typed records of functions
Java a generic Visitor<R> with accept; a second program with a sealed interface and record patterns
C# records and switch expressions with positional patterns
Go an interface with an unexported method, and type switches
Rust an enum and match
C++ std::variant and std::visit with a set of lambdas
PythonGitHub
from dataclasses import dataclass


@dataclass(frozen=True)
class Num:
    value: int


@dataclass(frozen=True)
class Add:
    left: "Expr"
    right: "Expr"


@dataclass(frozen=True)
class Mul:
    left: "Expr"
    right: "Expr"


type Expr = Num | Add | Mul


# Each operation is one function with a case for each kind of node.
def show(e: Expr) -> str:
    match e:
        case Num(value):
            return str(value)
        case Add(left, right):
            return f"({show(left)} + {show(right)})"
        case Mul(left, right):
            return f"({show(left)} * {show(right)})"


def evaluate(e: Expr) -> int:
    match e:
        case Num(value):
            return value
        case Add(left, right):
            return evaluate(left) + evaluate(right)
        case Mul(left, right):
            return evaluate(left) * evaluate(right)


def count(e: Expr) -> int:
    match e:
        case Num():
            return 1
        case Add(left, right) | Mul(left, right):
            return 1 + count(left) + count(right)


tree = Mul(Add(Num(2), Num(3)), Num(4))
print("show:", show(tree))
print("evaluate:", evaluate(tree))
print("nodes:", count(tree))
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5

The standard library has a visitor for Python's own syntax trees. ast.NodeVisitor.visit calls the method visit_ plus the class name of the node, and generic_visit visits the children:

import ast


class Counter(ast.NodeVisitor):
    def __init__(self):
        self.operators = []
        self.constants = 0

    def visit_BinOp(self, node):
        self.operators.append(type(node.op).__name__)
        self.generic_visit(node)  # go on into the left and right operands

    def visit_Constant(self, node):
        self.constants += 1


counter = Counter()
counter.visit(ast.parse("(2 + 3) * 4"))
print("operators:", counter.operators)
print("constants:", counter.constants)
Output
operators: ['Mult', 'Add']
constants: 3
  • Verdict: idiom. Frozen dataclasses are the node types, and a match statement with class patterns gives each operation a case for each node type. The positional patterns such as Add(left, right) work because a dataclass sets __match_args__.
  • The type Expr = ... statement names the union for a type checker. The interpreter does not check it, so a missing case returns None at run time. The node page shows this error and the fix with assert_never.
  • ast.NodeVisitor dispatches on the name of the class with getattr, so no accept method is needed. A visitor overrides only the node types that it cares about.
  • functools.singledispatch is another form. It picks a function by the type of the first argument.
#include <iostream>
#include <memory>
#include <string>
#include <variant>

struct Add;
struct Mul;
struct Num {
    int value;
};
using Expr = std::variant<Num, std::unique_ptr<Add>, std::unique_ptr<Mul>>;
struct Add {
    Expr left, right;
};
struct Mul {
    Expr left, right;
};

// overloaded turns a set of lambdas into one callable with an operator() for each type.
template <class... Fs>
struct overloaded : Fs... {
    using Fs::operator()...;
};

std::string show(const Expr& e) {
    return std::visit(
        overloaded{
            [](const Num& n) { return std::to_string(n.value); },
            [](const std::unique_ptr<Add>& a) { return "(" + show(a->left) + " + " + show(a->right) + ")"; },
            [](const std::unique_ptr<Mul>& m) { return "(" + show(m->left) + " * " + show(m->right) + ")"; },
        },
        e);
}

int evaluate(const Expr& e) {
    return std::visit(overloaded{
                          [](const Num& n) { return n.value; },
                          [](const std::unique_ptr<Add>& a) { return evaluate(a->left) + evaluate(a->right); },
                          [](const std::unique_ptr<Mul>& m) { return evaluate(m->left) * evaluate(m->right); },
                      },
                      e);
}

int count(const Expr& e) {
    return std::visit(overloaded{
                          [](const Num&) { return 1; },
                          [](const auto& node) { return 1 + count(node->left) + count(node->right); },
                      },
                      e);
}

Expr num(int v) { return Num{v}; }
Expr add(Expr l, Expr r) { return std::make_unique<Add>(Add{std::move(l), std::move(r)}); }
Expr mul(Expr l, Expr r) { return std::make_unique<Mul>(Mul{std::move(l), std::move(r)}); }

int main() {
    Expr tree = mul(add(num(2), num(3)), num(4));
    std::cout << "show: " << show(tree) << "\n";
    std::cout << "evaluate: " << evaluate(tree) << "\n";
    std::cout << "nodes: " << count(tree) << "\n";
}
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5
  • Verdict: stdlib. std::variant is a sum type in the library, and std::visit calls the overload that matches the alternative that the variant holds.
  • The call to std::visit does not compile if one alternative has no matching overload, so a missing case is a compile error, as in Rust.
  • Add and Mul contain Expr, so the variant holds them through std::unique_ptr. A Num needs no pointer.
  • In count, a generic lambda const auto& matches both pointer types. Overload resolution prefers the exact const Num& overload for numbers.
JavaGitHub
public class Main {
    // The classic form: each node has accept, and each operation is a Visitor.
    interface Visitor<R> {
        R num(Num n);

        R add(Add n);

        R mul(Mul n);
    }

    sealed interface Expr permits Num, Add, Mul {
        <R> R accept(Visitor<R> v);
    }

    record Num(int value) implements Expr {
        public <R> R accept(Visitor<R> v) {
            return v.num(this);
        }
    }

    record Add(Expr left, Expr right) implements Expr {
        public <R> R accept(Visitor<R> v) {
            return v.add(this);
        }
    }

    record Mul(Expr left, Expr right) implements Expr {
        public <R> R accept(Visitor<R> v) {
            return v.mul(this);
        }
    }

    static final class Show implements Visitor<String> {
        public String num(Num n) {
            return Integer.toString(n.value());
        }

        public String add(Add n) {
            return "(" + n.left().accept(this) + " + " + n.right().accept(this) + ")";
        }

        public String mul(Mul n) {
            return "(" + n.left().accept(this) + " * " + n.right().accept(this) + ")";
        }
    }

    static final class Evaluate implements Visitor<Integer> {
        public Integer num(Num n) {
            return n.value();
        }

        public Integer add(Add n) {
            return n.left().accept(this) + n.right().accept(this);
        }

        public Integer mul(Mul n) {
            return n.left().accept(this) * n.right().accept(this);
        }
    }

    static final class Count implements Visitor<Integer> {
        public Integer num(Num n) {
            return 1;
        }

        public Integer add(Add n) {
            return 1 + n.left().accept(this) + n.right().accept(this);
        }

        public Integer mul(Mul n) {
            return 1 + n.left().accept(this) + n.right().accept(this);
        }
    }

    public static void main(String[] args) {
        Expr tree = new Mul(new Add(new Num(2), new Num(3)), new Num(4));
        System.out.println("show: " + tree.accept(new Show()));
        System.out.println("evaluate: " + tree.accept(new Evaluate()));
        System.out.println("nodes: " + tree.accept(new Count()));
    }
}
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5

With a sealed interface, a switch with record patterns does the same work without accept. The compiler checks that the cases cover every permitted subtype:

public class Main {
    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 String show(Expr e) {
        return switch (e) {
            case Num(int v) -> Integer.toString(v);
            case Add(Expr l, Expr r) -> "(" + show(l) + " + " + show(r) + ")";
            case Mul(Expr l, Expr r) -> "(" + show(l) + " * " + show(r) + ")";
        };
    }

    static int evaluate(Expr e) {
        return switch (e) {
            case Num(int v) -> v;
            case Add(Expr l, Expr r) -> evaluate(l) + evaluate(r);
            case Mul(Expr l, Expr r) -> evaluate(l) * evaluate(r);
        };
    }

    static int count(Expr e) {
        return switch (e) {
            case Num n -> 1;
            case Add(Expr l, Expr r) -> 1 + count(l) + count(r);
            case Mul(Expr l, Expr r) -> 1 + count(l) + count(r);
        };
    }

    public static void main(String[] args) {
        Expr tree = new Mul(new Add(new Num(2), new Num(3)), new Num(4));
        System.out.println("show: " + show(tree));
        System.out.println("evaluate: " + evaluate(tree));
        System.out.println("nodes: " + count(tree));
    }
}
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5
  • Verdict: idiom. The first program is the double dispatch of Design Patterns. accept selects the visitor method by the class of the node, and the visitor object selects the operation.
  • The generic parameter R lets each visitor return its own type, so no visitor keeps its result in a field.
  • The second program has no visitor. The switch has no default, and it compiles because Expr is sealed and the cases cover Num, Add and Mul. A fourth record in permits makes each of these switches a compile error.
  • java.nio.file.FileVisitor with Files.walkFileTree is a visitor in the standard library. The walk calls the visitor before and after each directory and for each file.
Expr tree = new Mul(new Add(new Num(2), new Num(3)), new Num(4));
Console.WriteLine($"show: {Ops.Show(tree)}");
Console.WriteLine($"evaluate: {Ops.Evaluate(tree)}");
Console.WriteLine($"nodes: {Ops.Count(tree)}");

abstract record Expr;
sealed record Num(int Value) : Expr;
sealed record Add(Expr Left, Expr Right) : Expr;
sealed record Mul(Expr Left, Expr Right) : Expr;

static class Ops
{
    // Each operation is one switch expression with an arm for each kind of node.
    public static string Show(Expr e) => e switch
    {
        Num(var v) => v.ToString(),
        Add(var l, var r) => $"({Show(l)} + {Show(r)})",
        Mul(var l, var r) => $"({Show(l)} * {Show(r)})",
        _ => throw new ArgumentException($"unknown node {e}"),
    };

    public static int Evaluate(Expr e) => e switch
    {
        Num(var v) => v,
        Add(var l, var r) => Evaluate(l) + Evaluate(r),
        Mul(var l, var r) => Evaluate(l) * Evaluate(r),
        _ => throw new ArgumentException($"unknown node {e}"),
    };

    public static int Count(Expr e) => e switch
    {
        Num => 1,
        Add(var l, var r) => 1 + Count(l) + Count(r),
        Mul(var l, var r) => 1 + Count(l) + Count(r),
        _ => throw new ArgumentException($"unknown node {e}"),
    };
}
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5
  • Verdict: idiom. Records are the node types, and a switch expression with positional patterns gives each operation an arm for each type. A positional record has a Deconstruct method, so Add(var l, var r) binds the children.
  • Expr is an abstract record, so other code can add a subtype. The compiler cannot prove that three arms cover every subtype, so a switch without the _ arm gets warning CS8509. With the _ arm, a missing case fails at run time and not at compile time.
  • The classic form with Accept and an IVisitor<R> interface works too. It is the form to choose when the compiler must report a missing operation, because each visitor class must implement every method of the interface.
JavaScriptGitHub
class Num {
  constructor(value) {
    this.value = value;
  }
  accept(visitor) {
    return visitor.num(this);
  }
}

class Add {
  constructor(left, right) {
    this.left = left;
    this.right = right;
  }
  accept(visitor) {
    return visitor.add(this);
  }
}

class Mul {
  constructor(left, right) {
    this.left = left;
    this.right = right;
  }
  accept(visitor) {
    return visitor.mul(this);
  }
}

// Each visitor is one operation, with a method for each kind of node.
const show = {
  num: (n) => String(n.value),
  add: (n) => `(${n.left.accept(show)} + ${n.right.accept(show)})`,
  mul: (n) => `(${n.left.accept(show)} * ${n.right.accept(show)})`,
};

const evaluate = {
  num: (n) => n.value,
  add: (n) => n.left.accept(evaluate) + n.right.accept(evaluate),
  mul: (n) => n.left.accept(evaluate) * n.right.accept(evaluate),
};

const count = {
  num: () => 1,
  add: (n) => 1 + n.left.accept(count) + n.right.accept(count),
  mul: (n) => 1 + n.left.accept(count) + n.right.accept(count),
};

const tree = new Mul(new Add(new Num(2), new Num(3)), new Num(4));
console.log("show:", tree.accept(show));
console.log("evaluate:", tree.accept(evaluate));
console.log("nodes:", tree.accept(count));
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5
  • Verdict: idiom. This is the classic double dispatch. accept picks the method of the visitor by the class of the node, and the visitor picks the operation.
  • A visitor is a plain object of functions, so an operation needs no class. A visitor that lacks a method throws a TypeError only when the program reaches a node of that kind.
  • Without accept, a function can switch on node.constructor or on a kind field. The TypeScript example uses a kind field, so that the compiler can check the cases.
TypeScriptGitHub
type Expr =
  | { kind: "num"; value: number }
  | { kind: "add"; left: Expr; right: Expr }
  | { kind: "mul"; left: Expr; right: Expr };

// A visitor is a record with one function for each kind. The type makes all three required.
type Visitor<R> = {
  num: (value: number) => R;
  add: (left: R, right: R) => R;
  mul: (left: R, right: R) => R;
};

// fold walks the tree once and gives the visitor the results of the children.
function fold<R>(e: Expr, v: Visitor<R>): R {
  switch (e.kind) {
    case "num":
      return v.num(e.value);
    case "add":
      return v.add(fold(e.left, v), fold(e.right, v));
    case "mul":
      return v.mul(fold(e.left, v), fold(e.right, v));
    default: {
      const unknown: never = e;
      throw new Error(`unknown node ${JSON.stringify(unknown)}`);
    }
  }
}

const show: Visitor<string> = {
  num: (value) => String(value),
  add: (l, r) => `(${l} + ${r})`,
  mul: (l, r) => `(${l} * ${r})`,
};

const evaluate: Visitor<number> = {
  num: (value) => value,
  add: (l, r) => l + r,
  mul: (l, r) => l * r,
};

const count: Visitor<number> = {
  num: () => 1,
  add: (l, r) => 1 + l + r,
  mul: (l, r) => 1 + l + r,
};

const num = (value: number): Expr => ({ kind: "num", value });
const tree: Expr = {
  kind: "mul",
  left: { kind: "add", left: num(2), right: num(3) },
  right: num(4),
};

console.log("show:", fold(tree, show));
console.log("evaluate:", fold(tree, evaluate));
console.log("nodes:", fold(tree, count));
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5
  • Verdict: idiom. The nodes are a discriminated union on the kind field, and the visitor is a record of functions. tsc rejects a visitor that lacks a function for a kind.
  • fold holds the traversal, so the visitors do not recurse. Each function receives the results for the children. This answers the question of Design Patterns about who traverses the structure: here the code that owns the structure does.
  • The default case assigns e to a variable of type never. If a kind is added to Expr without a case, e has that kind there, and tsc rejects the assignment. The TypeScript handbook calls this exhaustiveness checking. Node strips the types and does not check them, so only tsc reports the error.
package main

import "fmt"

// Expr is a closed set by convention: only the types in this package have the method.
type Expr interface{ isExpr() }

type Num struct{ Value int }
type Add struct{ Left, Right Expr }
type Mul struct{ Left, Right Expr }

func (Num) isExpr() {}
func (Add) isExpr() {}
func (Mul) isExpr() {}

func show(e Expr) string {
	switch e := e.(type) {
	case Num:
		return fmt.Sprint(e.Value)
	case Add:
		return "(" + show(e.Left) + " + " + show(e.Right) + ")"
	case Mul:
		return "(" + show(e.Left) + " * " + show(e.Right) + ")"
	default:
		panic(fmt.Sprintf("unknown node %T", e))
	}
}

func evaluate(e Expr) int {
	switch e := e.(type) {
	case Num:
		return e.Value
	case Add:
		return evaluate(e.Left) + evaluate(e.Right)
	case Mul:
		return evaluate(e.Left) * evaluate(e.Right)
	default:
		panic(fmt.Sprintf("unknown node %T", e))
	}
}

func count(e Expr) int {
	switch e := e.(type) {
	case Num:
		return 1
	case Add:
		return 1 + count(e.Left) + count(e.Right)
	case Mul:
		return 1 + count(e.Left) + count(e.Right)
	default:
		panic(fmt.Sprintf("unknown node %T", e))
	}
}

func main() {
	tree := Mul{Add{Num{2}, Num{3}}, Num{4}}
	fmt.Println("show:", show(tree))
	fmt.Println("evaluate:", evaluate(tree))
	fmt.Println("nodes:", count(tree))
}
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5
  • Verdict: idiom. A type switch picks the case by the dynamic type of the interface value. Each operation is one function with a case for each node type.
  • The unexported method isExpr keeps other packages from adding node types. The compiler still does not check that a type switch covers every type, so each switch has a default that panics.
  • go/ast has a Visitor interface and a Walk function. Walk holds the traversal, and the visitor's Visit method returns the visitor to use for the children, or nil to skip them.
RustGitHub
enum Expr {
    Num(i64),
    Add(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
}

use Expr::*;

// Each operation is one function with a match. The compiler checks that each variant has an arm.
fn show(e: &Expr) -> String {
    match e {
        Num(v) => v.to_string(),
        Add(l, r) => format!("({} + {})", show(l), show(r)),
        Mul(l, r) => format!("({} * {})", show(l), show(r)),
    }
}

fn evaluate(e: &Expr) -> i64 {
    match e {
        Num(v) => *v,
        Add(l, r) => evaluate(l) + evaluate(r),
        Mul(l, r) => evaluate(l) * evaluate(r),
    }
}

fn count(e: &Expr) -> usize {
    match e {
        Num(_) => 1,
        Add(l, r) | Mul(l, r) => 1 + count(l) + count(r),
    }
}

fn main() {
    let tree = Mul(Box::new(Add(Box::new(Num(2)), Box::new(Num(3)))), Box::new(Num(4)));
    println!("show: {}", show(&tree));
    println!("evaluate: {}", evaluate(&tree));
    println!("nodes: {}", count(&tree));
}
Output
show: ((2 + 3) * 4)
evaluate: 20
nodes: 5
  • Verdict: native. An enum is a sum type, and a match must have an arm for each variant. A variant added to Expr makes each of these functions a compile error until it gets an arm.
  • Box gives a recursive enum a known size. Without it, an Expr would contain itself.
  • The or-pattern Add(l, r) | Mul(l, r) shares one arm, because both variants bind the same names with the same types.
  • A Visitor trait with a default method for each variant is the classic form in Rust. It fits a tree with many variants, where most operations care about a few of them and want a default for the rest.

Consequences

Design Patterns lists these consequences.1 With visitors, an operation is cheap to add. A visitor gathers the code of one operation and separates unrelated operations. Adding a ConcreteElement class is hard, because each visitor needs a method for it. A visitor can visit classes that have no common parent, which an iterator cannot do. A visitor can accumulate state as it visits, such as a symbol table, so that the state does not travel in arguments. And a visitor breaks encapsulation, because the elements must give it enough access to do its work.

The pattern also has costs that come from the language. In a language with single dispatch, the accept methods are boilerplate that exists only to recover the class of the node. Norvig says that C++ encourages bookkeeping classes, and that the Visitor pattern serves only to get around this restriction.3 A visitor that keeps its result in a field cannot be called again while it runs, unless it saves and restores the field. A generic visitor that returns a value, such as Visitor<R> in the Java example, avoids this.

When not to use it

Do not use a visitor when the kinds of element change more often than the operations. Each added class then changes every visitor. Put the operations in the classes, as methods.

Do not write accept methods in a language with sum types and pattern matching. An enum and a match give the same separation, with less code and an exhaustiveness check.

Do not use a visitor for one operation. A function with a match, or a method on each class, is shorter. A visitor pays off when there are many operations on a stable set of classes.

Functions as visitors. Norvig lists Visitor among the four patterns that first-class functions affect.3 A visitor can be a record of functions, as in the JavaScript and TypeScript examples. Python's functools.singledispatch picks a function by the type of its first argument, which is single dispatch without accept.13 Norvig's slide on multimethods shows dispatch on the classes of more than one argument, which removes the need for double dispatch.3

Reflective dispatch. Python's ast.NodeVisitor.visit builds the method name 'visit_' plus the class name of the node and looks it up with getattr. A node with no such method goes to generic_visit.4 The visitor needs no interface, and the nodes need no accept. The cost is that a misspelled method name is never called, and nothing reports it.

Composite and Interpreter. Design Patterns relates Visitor to Composite, because a visitor can apply an operation over a composite structure, and to Interpreter, because a visitor can do the interpretation.1 See Composite pattern.

Iterator. An iterator visits the elements of a structure in order and gives them to the caller. A visitor runs code that depends on the kind of each element. A walk such as Java's Files.walkFileTree combines both: it traverses the tree and calls a FileVisitor for each directory and file.11 See Iterator.

Strategy. A visitor is a strategy with one method for each kind of element. See Strategy pattern.

Refactoring. Kerievsky's Move Accumulation to Visitor moves code that gathers data from many classes into a visitor.14

Known uses

  • CPython: ast.NodeVisitor at v3.14.0 dispatches on the class name of each node of a Python syntax tree.4
  • Go: go/ast.Walk traverses a Go syntax tree in depth-first order and calls a Visitor for each node.12
  • Java: java.nio.file.FileVisitor is called by Files.walkFileTree before and after each directory and for each file.11
  • C++: std::visit applies a callable to the alternative that a std::variant holds.10

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Visitor (Intent, Motivation, Applicability, Participants, Collaborations, Consequences, Implementation, Related Patterns)
  2. Philip Wadler, The Expression Problem, email to the java-genericity mailing list, 12 November 1998, opening section and section 1, A solution
  3. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (Visitor is among the patterns affected by first-class functions), slide 23 (The Type/Operation Matrix), slide 24 (Multimethods) and slide 61 (Class-Oriented or Class-Obsessed?)
  4. CPython v3.14.0 source, Lib/ast.py, class NodeVisitor, lines 482 to 516
  5. The Python Standard Library, typing, Python 3.14, typing.assert_never
  6. The Java Language Specification, Java SE 25 Edition, 14.11.1.1 Exhaustive Switch Blocks
  7. JEP 441, Pattern Matching for switch, Description, Exhaustiveness of switch expressions and statements, and Exhaustiveness and sealed classes
  8. The Rust Programming Language, chapter 6.2, The match Control Flow Construct, Matches Are Exhaustive
  9. TypeScript Handbook, Narrowing, Exhaustiveness checking
  10. Working Draft, Programming Languages, C++, [variant.visit] Visitation
  11. Java SE 25 API, java.nio.file.FileVisitor, interface description
  12. Go standard library, package go/ast, func Walk and type Visitor
  13. The Python Standard Library, functools, Python 3.14, functools.singledispatch
  14. Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 10, Accumulation, Move Accumulation to Visitor

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/JQCQK2/text.yaml