Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 57 ยท Behavioral Patterns

Visitor, Interpreter and Null Object

Learn Visitor and double dispatch to add operations to a class hierarchy, Interpreter for small languages, and Null Object to remove null checks.

This lesson covers the last three classic behavioral patterns. They are quite different from each other, but each answers a concrete question. Visitor: how do I add a new operation to a family of classes without editing every class? Interpreter: how do I represent and evaluate sentences of a tiny language? Null Object: how do I stop writing if (x != null) everywhere?

We will run all three on small examples. Visitor and Interpreter fit together nicely, because an expression tree is the perfect structure to visit.

Three patterns, three questions

Visitor Add operations without touching the classes.
Interpreter Evaluate a small language as a tree of objects.
Null Object Replace null with an object that does nothing.
1 / 2

Visitor and double dispatch

Imagine a small shape hierarchy: Circle, Rectangle, Group. You need to compute area, then render to SVG, then export to JSON. The obvious way is to add a method to every class for every new job. Each new operation edits every class, and the classes fill up with unrelated code.

The Visitor pattern moves each operation into its own object, the visitor. The element classes keep just one method, accept(visitor), which calls back the visitor method for its own type. That trick is called double dispatch: the program picks the code to run by two types, the element's type and the visitor's type.

sequenceDiagram
    participant C as Client
    participant E as Circle (element)
    participant V as AreaVisitor
    C->>E: accept(visitor)
    E->>V: visitCircle(this)
    V-->>C: area

First call: the element is chosen at run time. Second call: the element names its own type to the visitor.

Languages like Java and C++ need this trick because they dispatch overloaded methods on the declared type of the argument. JavaScript and Python can emulate it with a method name, as the code below shows.

JS Two visitors over one shape tree

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Adding a third operation (say, JSON export) means writing one new class and no changes to Circle, Rectangle or Group. That is the strength of Visitor.

The trade-off

Visitor flips the usual extensibility trade-off:

  • Adding a new operation is easy: write a new visitor.
  • Adding a new element type is hard: every visitor needs a new method, and the compiler (in typed languages) forces you to update them all.

So Visitor pays off when the element hierarchy is stable and the set of operations grows. Compilers are the standard case: syntax-tree node types change rarely, while passes (type checking, optimization, code generation, pretty printing) keep growing. If your classes change often and operations rarely, plain polymorphic methods are better.

Visitor also needs elements to expose enough of their state for visitors to work, which weakens encapsulation. Dynamic languages often replace it with match statements or a function keyed on a type tag, which is fine when the "closed hierarchy" is clear.

Interpreter: a language as objects

The Interpreter pattern represents a grammar as a class per rule and evaluates a sentence by walking the tree built from those classes. Each node has an evaluate(context) method. Terminal nodes (numbers, variables) return a value; non-terminal nodes (addition, comparison) combine the results of their children.

It is a good fit for small, stable languages: search filters, pricing rules, validation rules, simple formulas. For large grammars, hand-written node classes become unwieldy, and a parser generator or an existing library is the better choice.

JS A tiny expression interpreter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The rule is data: you can build it from a configuration file, print it, store it, or evaluate it against thousands of orders. Notice that toString is a second operation on the same tree. If you needed many such operations, you would combine Interpreter with Visitor, as most compilers do: the tree is built once and each pass is a visitor.

Null Object: an object that does nothing

A method that may return null forces every caller to check it. Forget one check and you get a NullPointerException or TypeError. The Null Object pattern replaces null with a real object that implements the same interface and does nothing (or returns a safe default).

JS Removing null checks with a Null Object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

PaymentService.pay contains no if (this.logger). Callers who do not care about logging pass nothing and get the silent object.

Use Null Object when "do nothing" is a sensible, expected behavior. Do not use it to hide real errors. A missing record that must exist should throw, not return a quiet stand-in that lets the program continue with wrong data. Related tools you will meet in practice are Java's Optional, Kotlin's and Swift's nullable types, and Collections.emptyList(), which returns an empty list instead of null. These push the decision into the type system or into a ready-made empty object.

A Null Object is often immutable and shared, so a single instance (like guest above) is enough.

Putting them side by side

Pattern Core idea Best when Watch out for
Visitor Move operations out of the classes, dispatch on two types Stable hierarchy, growing operations Adding element types is costly
Interpreter One class per grammar rule Small, stable languages Large grammars become messy
Null Object A do-nothing implementation instead of null Optional collaborators Hiding errors that should fail

For other behavioral patterns see Strategy, Chain of Responsibility and Mediator and Memento. A tree of nodes that all share one interface is a Composite, which is exactly what Visitor and Interpreter walk.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is double dispatch in the Visitor pattern?

    accept() selects the element's behavior, and it calls back a visitor method named for the element, so both types decide which code runs.
  2. 2. When is Visitor a good choice?

    New operations are a single new visitor class, while a new element type means editing every visitor, so Visitor suits stable hierarchies.
  3. 3. What does an Interpreter node's evaluate() method typically do?

    Terminal nodes return their own value, and non-terminal nodes evaluate their children and combine the results.
  4. 4. What is the main benefit of a Null Object?

    Because the null object has the same interface and a harmless behavior, code can call it without branching.
  5. 5. In which case should you NOT return a Null Object?

    A missing required record is an error. A quiet stand-in would hide it and let the program continue with wrong data.

Summary

  • Visitor puts each operation in its own object and uses accept to dispatch on two types (double dispatch).
  • Visitor makes new operations easy and new element types hard, so use it for stable hierarchies.
  • Interpreter models a small grammar as a tree of objects that evaluate themselves; it is data you can build, print and reuse.
  • Combine Interpreter with Visitor when you need many passes over the same tree.
  • Null Object replaces null with a harmless object of the same interface to remove checks.
  • Do not use a Null Object to hide errors that should fail loudly.

Next lesson: Repository and Unit of Work.