Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Visitor

Intent

Add new operations to a family of shapes without editing the shapes, by moving each operation into a visitor object the shapes accept.

Motivation

A drawing holds circles and squares. Area math lives naturally with each shape, but each new report — export, pricing, validation — would force every shape file open for edits. Letting shapes accept a visitor and call back into it flips the dependency: new operations arrive as new visitors, and shapes only keep one stable accept method.

Structure

flowchart LR
  Client[Client] --> V[Shape Visitor]
  V --> Area[Area Visitor]
  V --> Export[Export Visitor]
  Circle[Circle Element] --> V
  Square[Square Element] --> V
  • Elements (Circle, Square) — hold their own data and expose one accept method.
  • Visitor (Area, Export) — implements one operation across every element type.
  • Client — pairs elements with whichever visitor it needs.

Consequences

  • Benefit: new operations cost one new visitor, zero shape edits; all of one operation’s logic sits together.
  • Cost: adding a new shape type forces every visitor to grow a branch — cheap operations, pricey elements.

Basic Recap

Visitor adds an operation over a stable set of element types without placing that operation in every element class. Elements accept a visitor and dispatch to the method for their concrete type, while a visitor accumulates or returns the operation’s result. This is useful when new analyses are common but new element kinds are rare. Adding an element kind still requires updating every concrete visitor, which is the pattern’s central trade-off.

Complex Scenario

An infrastructure configuration model has stable nodes for compute, database, queue, and network resources. Separate visitors validate security policy, estimate monthly cost, and generate an execution manifest without turning each resource class into a home for all three concerns. A validation visitor returns structured findings attached to resource paths, while the cost visitor combines usage context with node attributes. The resource graph stays independent of the reporting and policy tools built over it.

Edge cases

  • Ordering: A manifest visitor must honor dependencies between resources rather than treating traversal order as deployment order; dependency analysis belongs in the operation or an earlier plan.
  • Partial failure: One malformed resource should produce a located finding and let validation continue where safe, instead of losing all other errors to the first exception.
  • Memory pressure: Reusing one visitor across large graphs can retain every intermediate result, so accumulation needs bounded output or streaming.
  • Concurrency: A mutable visitor instance cannot be shared by simultaneous analyses unless its accumulation is isolated per traversal.

Traversal control and operation logic should be separated enough to handle cycles or shared nodes without duplicating policy code.

Sketch (illustrative pseudocode, not runnable):

SecurityValidator.visitDatabase(node, path):
    if node.publiclyReachable and not node.explicitlyApproved:
        findings.add(path, PUBLIC_DATABASE)
    for child in node.children:
        child.accept(this, path.extend(child.name))

Analyze.run(root):
    validator = SecurityValidator(findings = StreamSink(limit))
    traversal.walkOnce(root, validator)  # visited identity set prevents cycles
    return validator.findings.summary()

When to Use / When Not to Use

Use when:

  • Element types are stable but operations over them keep growing (area, export, pricing, checks).
  • You want each operation’s cross-type logic in one reviewable unit.

Avoid when:

  • New element types appear often — every addition ripples through all visitors (prefer plain polymorphism then).

Examples

  • examples/elixir/visitor/
  • examples/dart/visitor/
  • examples/go/visitor/
  • examples/rust/visitor/

Expected outcome: an area visitor prices a circle and a square, then an export visitor reports both shapes.

Anti-pattern / Failure Mode

  • Misuse: A visitor over an unstable element set — every new element breaks all visitors.

  • Review signal: Visitors that need private element internals to work.

  • Misuse symptom: The element hierarchy changes weekly, forcing edits to a dozen visitors, or visitors use type tests because elements lack proper double dispatch. Visitors that mutate resources while validating also blur analysis with transformation and make results traversal-dependent.

  • Review signal: Look for empty visit methods added just to compile after a new node type, huge visitors handling unrelated operations, and shared mutable accumulators. If new element kinds are more frequent than new operations, ordinary polymorphic methods on the elements usually create less churn.

  • Iterator — add operations vs walk storage.
  • Composite — operate over stable trees.
  • Open/Closed — new operations without editing elements.

Exercise

Add a triangle element — update every visitor and note the ripple. Then add a perimeter visitor touching no element files, and compare the two change shapes.

Self-check

  • Who changes when a new operation appears?
    AnswerOnly the new visitor — elements keep their single accept method untouched.
  • Who changes when a new element appears?
    AnswerEvery visitor needs a new branch, which is this pattern’s main cost.
  • How does accept dispatch work?
    AnswerDouble dispatch: the element’s accept calls back the visitor method for its own type, so the operation picks the right branch per element.