# Visitor: New Jobs Without Touching Every Class

When every new job on a tree of objects (describe it, count it, check it) means a new method in every class of the tree, each job ends up scattered across all of them; the Visitor pattern puts each job in one object with a method for each kind of piece, so a new job is one new class and the pieces never change.

Freelancer · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Add a new job to a tree of objects as a visitor, without changing the classes in the tree
- Spot the smells that point to Visitor: every new job adds a method to every class in a family that rarely changes
- Choose between a visitor and a method in each class by whether new jobs or new kinds of piece come more often

## Key takeaways

- The smell: every new job means a new method in every class of a family, and the classes fill up with jobs that aren't theirs.
- The cause: the kinds of piece rarely change, but the jobs keep coming, and each job is cut up across every class.
- The fix: each job becomes a visitor, one object with a method for each kind of piece; a piece only hands itself to the visitor.
- Pattern matching is the modern version. Both make a new job easy and a new kind of piece harder, so pick by which comes more often.

**Before this:** *Interpreter: A Little Language for Rules*, which builds the coupon-rule tree this lesson works on, and interfaces.

In the last lesson, each piece of a Trailhead Outfitters coupon rule had one job: answer "does this order qualify?". Now marketing wants more from the admin screen: show every rule in plain words, say how many pieces it has (so nobody builds one too big to follow), and warn them when a rule can never work. Each is a new job for the whole tree. By the end of this lesson you'll have met the pattern that gives a tree new jobs without opening its classes, *Visitor*.

## The symptom: every job lives in every class

Two of the jobs are already in, added the way anyone would add them first: a `describe` method and a `count` method in each of the five classes.

```csharp
Dictionary<string, IRule> rules = new Dictionary<string, IRule>
{
    ["TRAIL10"] = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))),
    ["BOTTLE"] = new And(new Has("jacket"), new Not(new Has("bottle"))),
    ["SUMMIT15"] = new And(new Has("boot"), new TotalOver(100)),
};
foreach (KeyValuePair<string, IRule> rule in rules)
{
    Console.WriteLine($"{rule.Key}: {rule.Value.Describe()}");
    Console.WriteLine($"  {rule.Value.Count()} pieces");
}

// Qualifies(order) is still in every class; it's left out here to keep the code short.
interface IRule
{
    string Describe();
    int Count();
}

class TotalOver(int amount) : IRule
{
    public string Describe() => $"total over ${amount}";
    public int Count() => 1;
}

class Has(string kind) : IRule
{
    public string Describe() => $"has a {kind}";
    public int Count() => 1;
}

class And(IRule left, IRule right) : IRule
{
    public string Describe() => $"{Words.Part(left)} and {Words.Part(right)}";
    public int Count() => 1 + left.Count() + right.Count();
}

class Or(IRule left, IRule right) : IRule
{
    public string Describe() => $"{Words.Part(left)} or {Words.Part(right)}";
    public int Count() => 1 + left.Count() + right.Count();
}

class Not(IRule rule) : IRule
{
    public string Describe() => $"not {Words.Part(rule)}";
    public int Count() => 1 + rule.Count();
}

static class Words
{
    // An "and" or an "or" inside another piece gets brackets, so the words read the right way.
    public static string Part(IRule rule) => rule is And or Or ? $"({rule.Describe()})" : rule.Describe();
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces
BOTTLE: has a jacket and not has a bottle
  4 pieces
SUMMIT15: has a boot and total over $100
  3 pieces
```

```java
// qualifies(order) is still in every class; it's left out here to keep the code short.
interface Rule {
    String describe();
    int count();
}

record TotalOver(int amount) implements Rule {
    public String describe() { return "total over $" + amount; }
    public int count() { return 1; }
}

record Has(String kind) implements Rule {
    public String describe() { return "has a " + kind; }
    public int count() { return 1; }
}

record And(Rule left, Rule right) implements Rule {
    public String describe() { return part(left) + " and " + part(right); }
    public int count() { return 1 + left.count() + right.count(); }
}

record Or(Rule left, Rule right) implements Rule {
    public String describe() { return part(left) + " or " + part(right); }
    public int count() { return 1 + left.count() + right.count(); }
}

record Not(Rule rule) implements Rule {
    public String describe() { return "not " + part(rule); }
    public int count() { return 1 + rule.count(); }
}

// An "and" or an "or" inside another piece gets brackets, so the words read the right way.
static String part(Rule rule) {
    return rule instanceof And || rule instanceof Or ? "(" + rule.describe() + ")" : rule.describe();
}

void main() {
    Map<String, Rule> rules = new LinkedHashMap<>();
    rules.put("TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))));
    rules.put("BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle"))));
    rules.put("SUMMIT15", new And(new Has("boot"), new TotalOver(100)));
    for (String code : rules.keySet()) {
        IO.println(code + ": " + rules.get(code).describe());
        IO.println("  " + rules.get(code).count() + " pieces");
    }
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces
BOTTLE: has a jacket and not has a bottle
  4 pieces
SUMMIT15: has a boot and total over $100
  3 pieces
```

```python
# qualifies(order) is still in every class; it's left out here to keep the code short.
class TotalOver:
    def __init__(self, amount):
        self.amount = amount

    def describe(self):
        return f"total over ${self.amount}"

    def count(self):
        return 1


class Has:
    def __init__(self, kind):
        self.kind = kind

    def describe(self):
        return f"has a {self.kind}"

    def count(self):
        return 1


class And:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def describe(self):
        return f"{part(self.left)} and {part(self.right)}"

    def count(self):
        return 1 + self.left.count() + self.right.count()


class Or:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def describe(self):
        return f"{part(self.left)} or {part(self.right)}"

    def count(self):
        return 1 + self.left.count() + self.right.count()


class Not:
    def __init__(self, rule):
        self.rule = rule

    def describe(self):
        return f"not {part(self.rule)}"

    def count(self):
        return 1 + self.rule.count()


def part(rule):
    """An "and" or an "or" inside another piece gets brackets, so the words read the right way."""
    text = rule.describe()
    return f"({text})" if isinstance(rule, (And, Or)) else text


rules = {
    "TRAIL10": And(TotalOver(50), Or(Has("shoe"), Has("jacket"))),
    "BOTTLE": And(Has("jacket"), Not(Has("bottle"))),
    "SUMMIT15": And(Has("boot"), TotalOver(100)),
}
for code, rule in rules.items():
    print(f"{code}: {rule.describe()}")
    print(f"  {rule.count()} pieces")
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces
BOTTLE: has a jacket and not has a bottle
  4 pieces
SUMMIT15: has a boot and total over $100
  3 pieces
```

```javascript
// qualifies(order) is still in every class; it's left out here to keep the code short.
class TotalOver {
  constructor(amount) { this.amount = amount; }
  describe() { return `total over $${this.amount}`; }
  count() { return 1; }
}

class Has {
  constructor(kind) { this.kind = kind; }
  describe() { return `has a ${this.kind}`; }
  count() { return 1; }
}

class And {
  constructor(left, right) { this.left = left; this.right = right; }
  describe() { return `${part(this.left)} and ${part(this.right)}`; }
  count() { return 1 + this.left.count() + this.right.count(); }
}

class Or {
  constructor(left, right) { this.left = left; this.right = right; }
  describe() { return `${part(this.left)} or ${part(this.right)}`; }
  count() { return 1 + this.left.count() + this.right.count(); }
}

class Not {
  constructor(rule) { this.rule = rule; }
  describe() { return `not ${part(this.rule)}`; }
  count() { return 1 + this.rule.count(); }
}

// An "and" or an "or" inside another piece gets brackets, so the words read the right way.
function part(rule) {
  return rule instanceof And || rule instanceof Or ? `(${rule.describe()})` : rule.describe();
}

const rules = new Map([
  ["TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")))],
  ["BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle")))],
  ["SUMMIT15", new And(new Has("boot"), new TotalOver(100))],
]);
for (const [code, rule] of rules) {
  console.log(`${code}: ${rule.describe()}`);
  console.log(`  ${rule.count()} pieces`);
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces
BOTTLE: has a jacket and not has a bottle
  4 pieces
SUMMIT15: has a boot and total over $100
  3 pieces
```

```typescript
// qualifies(order) is still in every class; it's left out here to keep the code short.
interface Rule {
  describe(): string;
  count(): number;
}

class TotalOver implements Rule {
  amount: number;
  constructor(amount: number) { this.amount = amount; }
  describe(): string { return `total over $${this.amount}`; }
  count(): number { return 1; }
}

class Has implements Rule {
  kind: string;
  constructor(kind: string) { this.kind = kind; }
  describe(): string { return `has a ${this.kind}`; }
  count(): number { return 1; }
}

class And implements Rule {
  left: Rule;
  right: Rule;
  constructor(left: Rule, right: Rule) { this.left = left; this.right = right; }
  describe(): string { return `${part(this.left)} and ${part(this.right)}`; }
  count(): number { return 1 + this.left.count() + this.right.count(); }
}

class Or implements Rule {
  left: Rule;
  right: Rule;
  constructor(left: Rule, right: Rule) { this.left = left; this.right = right; }
  describe(): string { return `${part(this.left)} or ${part(this.right)}`; }
  count(): number { return 1 + this.left.count() + this.right.count(); }
}

class Not implements Rule {
  rule: Rule;
  constructor(rule: Rule) { this.rule = rule; }
  describe(): string { return `not ${part(this.rule)}`; }
  count(): number { return 1 + this.rule.count(); }
}

// An "and" or an "or" inside another piece gets brackets, so the words read the right way.
function part(rule: Rule): string {
  return rule instanceof And || rule instanceof Or ? `(${rule.describe()})` : rule.describe();
}

const rules = new Map<string, Rule>([
  ["TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")))],
  ["BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle")))],
  ["SUMMIT15", new And(new Has("boot"), new TotalOver(100))],
]);
for (const [code, rule] of rules) {
  console.log(`${code}: ${rule.describe()}`);
  console.log(`  ${rule.count()} pieces`);
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces
BOTTLE: has a jacket and not has a bottle
  4 pieces
SUMMIT15: has a boot and total over $100
  3 pieces
```

SUMMIT15 never matches anyone. Marketing picked "boot", but the store files hiking boots under "shoe", so no order will ever "have a boot". The third job, a checker that catches this, means a third method in all five classes. The job after that (the rules saved as text for the screen, say) means a fourth.

Read it as a doctor would:

- **The symptom:** each new job means a new method in every class of the family, and the classes collect jobs that have nothing to do with checking a coupon.
- **The cause:** the family is stable (five kinds of piece, and nobody has asked for a sixth), but the jobs keep coming, and every job is cut into five parts, one in each class. To read how `describe` works, you open five classes.
- **The cure:** coming up, once we've tried the obvious fixes.

## What would you try?

**Add `check()` to all five classes.** It works, but the checker's logic is spread over five places, and the classes keep growing.

**Write each job as one function full of `if (rule is And) … else if (rule is Or) …`.** This puts each job in one place, which is what we want. But nothing reminds you to handle every kind: forget `Not`, and the checker quietly skips everything under it. Keep this idea in mind; it comes back, with help, in the modern version.

**Move the jobs into a base class all five inherit from.** The same scattering, with one more layer to read.

What we want: each job in one place, every kind of piece handled for sure, and the five piece classes never touched again.

## The everyday version: the home inspector

A home inspector visits a house with one checklist, which has a section for each kind of room: kitchen (stove, outlets), bathroom (leaks, the fan), bedroom (smoke alarm). The house doesn't change for the inspection; each room lets the inspector in, and the inspector does the kitchen part of the list in the kitchen. Next week an electrician comes through the same rooms with a different checklist. A new kind of visit is a new checklist. The catch: a new kind of room, say a garage, needs a new section on every checklist.

![A home inspector with a clipboard walking through a house drawn in cross-section, standing in the kitchen, with the bathroom and the bedroom beside it; the rooms are unchanged, and the clipboard's checklist has one section for each kind of room, headed "Kitchen", "Bathroom" and "Bedroom"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/9680c4812dbd47c28087e885f92991a7.webp)

## The fix: one visitor for each job

**The fix in one sentence:** each job becomes a *visitor*, one object with a method for each kind of piece, and each piece only knows how to hand itself to a visitor.

![Visitor's roles: the screen hands a job to a piece of a rule, which calls the job's method for its own kind. The jobs, describe, count and check, are each a kind of job, in a dashed fence of what changes; the pieces (total over, has a, and, or, not) sit outside and never change](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/cd090b567e59431c8d5377525613590c.webp)

Each piece gets one tiny method, `accept`, and each job becomes a class of its own:

```csharp
Dictionary<string, IRule> rules = new Dictionary<string, IRule>
{
    ["TRAIL10"] = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))),
    ["BOTTLE"] = new And(new Has("jacket"), new Not(new Has("bottle"))),
    ["SUMMIT15"] = new And(new Has("boot"), new TotalOver(100)),
};
foreach (KeyValuePair<string, IRule> rule in rules)
{
    List<string> problems = rule.Value.Accept(new KindChecker());
    Console.WriteLine($"{rule.Key}: {rule.Value.Accept(new Describer())}");
    Console.WriteLine($"  {rule.Value.Accept(new Counter())} pieces, {(problems.Count > 0 ? string.Join(", ", problems) : "no problems")}");
}

// Each piece only knows how to hand itself to a visitor.
interface IRule { T Accept<T>(IRuleVisitor<T> visitor); }

record TotalOver(int Amount) : IRule { public T Accept<T>(IRuleVisitor<T> visitor) => visitor.VisitTotalOver(this); }
record Has(string Kind) : IRule { public T Accept<T>(IRuleVisitor<T> visitor) => visitor.VisitHas(this); }
record And(IRule Left, IRule Right) : IRule { public T Accept<T>(IRuleVisitor<T> visitor) => visitor.VisitAnd(this); }
record Or(IRule Left, IRule Right) : IRule { public T Accept<T>(IRuleVisitor<T> visitor) => visitor.VisitOr(this); }
record Not(IRule Rule) : IRule { public T Accept<T>(IRuleVisitor<T> visitor) => visitor.VisitNot(this); }

// A visitor is one job, with a method for each kind of piece.
interface IRuleVisitor<T>
{
    T VisitTotalOver(TotalOver rule);
    T VisitHas(Has rule);
    T VisitAnd(And rule);
    T VisitOr(Or rule);
    T VisitNot(Not rule);
}

class Describer : IRuleVisitor<string>
{
    public string VisitTotalOver(TotalOver rule) => $"total over ${rule.Amount}";
    public string VisitHas(Has rule) => $"has a {rule.Kind}";
    public string VisitAnd(And rule) => $"{Part(rule.Left)} and {Part(rule.Right)}";
    public string VisitOr(Or rule) => $"{Part(rule.Left)} or {Part(rule.Right)}";
    public string VisitNot(Not rule) => $"not {Part(rule.Rule)}";

    // An "and" or an "or" inside another piece gets brackets, so the words read the right way.
    private string Part(IRule rule) => rule is And or Or ? $"({rule.Accept(this)})" : rule.Accept(this);
}

class Counter : IRuleVisitor<int>
{
    public int VisitTotalOver(TotalOver rule) => 1;
    public int VisitHas(Has rule) => 1;
    public int VisitAnd(And rule) => 1 + rule.Left.Accept(this) + rule.Right.Accept(this);
    public int VisitOr(Or rule) => 1 + rule.Left.Accept(this) + rule.Right.Accept(this);
    public int VisitNot(Not rule) => 1 + rule.Rule.Accept(this);
}

// The new job: no piece class changed to add it.
class KindChecker : IRuleVisitor<List<string>>
{
    private static readonly List<string> Sold = new List<string> { "shoe", "jacket", "bottle", "socks" };

    public List<string> VisitTotalOver(TotalOver rule) => new List<string>();
    public List<string> VisitHas(Has rule) => Sold.Contains(rule.Kind) ? new List<string>() : new List<string> { $"the store sells no \"{rule.Kind}\"" };
    public List<string> VisitAnd(And rule) => rule.Left.Accept(this).Concat(rule.Right.Accept(this)).ToList();
    public List<string> VisitOr(Or rule) => rule.Left.Accept(this).Concat(rule.Right.Accept(this)).ToList();
    public List<string> VisitNot(Not rule) => rule.Rule.Accept(this);
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```java
// Each piece only knows how to hand itself to a visitor.
interface Rule { <T> T accept(RuleVisitor<T> visitor); }

record TotalOver(int amount) implements Rule { public <T> T accept(RuleVisitor<T> visitor) { return visitor.visitTotalOver(this); } }
record Has(String kind) implements Rule { public <T> T accept(RuleVisitor<T> visitor) { return visitor.visitHas(this); } }
record And(Rule left, Rule right) implements Rule { public <T> T accept(RuleVisitor<T> visitor) { return visitor.visitAnd(this); } }
record Or(Rule left, Rule right) implements Rule { public <T> T accept(RuleVisitor<T> visitor) { return visitor.visitOr(this); } }
record Not(Rule rule) implements Rule { public <T> T accept(RuleVisitor<T> visitor) { return visitor.visitNot(this); } }

// A visitor is one job, with a method for each kind of piece.
interface RuleVisitor<T> {
    T visitTotalOver(TotalOver rule);
    T visitHas(Has rule);
    T visitAnd(And rule);
    T visitOr(Or rule);
    T visitNot(Not rule);
}

static class Describer implements RuleVisitor<String> {
    public String visitTotalOver(TotalOver rule) { return "total over $" + rule.amount(); }
    public String visitHas(Has rule) { return "has a " + rule.kind(); }
    public String visitAnd(And rule) { return part(rule.left()) + " and " + part(rule.right()); }
    public String visitOr(Or rule) { return part(rule.left()) + " or " + part(rule.right()); }
    public String visitNot(Not rule) { return "not " + part(rule.rule()); }

    // An "and" or an "or" inside another piece gets brackets, so the words read the right way.
    private String part(Rule rule) {
        return rule instanceof And || rule instanceof Or ? "(" + rule.accept(this) + ")" : rule.accept(this);
    }
}

static class Counter implements RuleVisitor<Integer> {
    public Integer visitTotalOver(TotalOver rule) { return 1; }
    public Integer visitHas(Has rule) { return 1; }
    public Integer visitAnd(And rule) { return 1 + rule.left().accept(this) + rule.right().accept(this); }
    public Integer visitOr(Or rule) { return 1 + rule.left().accept(this) + rule.right().accept(this); }
    public Integer visitNot(Not rule) { return 1 + rule.rule().accept(this); }
}

// The new job: no piece class changed to add it.
static class KindChecker implements RuleVisitor<List<String>> {
    private static final List<String> SOLD = List.of("shoe", "jacket", "bottle", "socks");

    public List<String> visitTotalOver(TotalOver rule) { return List.of(); }
    public List<String> visitHas(Has rule) { return SOLD.contains(rule.kind()) ? List.of() : List.of("the store sells no \"" + rule.kind() + "\""); }
    public List<String> visitAnd(And rule) { return both(rule.left().accept(this), rule.right().accept(this)); }
    public List<String> visitOr(Or rule) { return both(rule.left().accept(this), rule.right().accept(this)); }
    public List<String> visitNot(Not rule) { return rule.rule().accept(this); }

    private List<String> both(List<String> first, List<String> second) {
        List<String> all = new ArrayList<>(first);
        all.addAll(second);
        return all;
    }
}

void main() {
    Map<String, Rule> rules = new LinkedHashMap<>();
    rules.put("TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))));
    rules.put("BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle"))));
    rules.put("SUMMIT15", new And(new Has("boot"), new TotalOver(100)));
    for (String code : rules.keySet()) {
        Rule rule = rules.get(code);
        List<String> problems = rule.accept(new KindChecker());
        IO.println(code + ": " + rule.accept(new Describer()));
        IO.println("  " + rule.accept(new Counter()) + " pieces, " + (problems.isEmpty() ? "no problems" : String.join(", ", problems)));
    }
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```python
# Each piece only knows how to hand itself to a visitor.
class TotalOver:
    def __init__(self, amount):
        self.amount = amount

    def accept(self, visitor):
        return visitor.visit_total_over(self)


class Has:
    def __init__(self, kind):
        self.kind = kind

    def accept(self, visitor):
        return visitor.visit_has(self)


class And:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def accept(self, visitor):
        return visitor.visit_and(self)


class Or:
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def accept(self, visitor):
        return visitor.visit_or(self)


class Not:
    def __init__(self, rule):
        self.rule = rule

    def accept(self, visitor):
        return visitor.visit_not(self)


# A visitor is one job, with a method for each kind of piece.
class Describer:
    def visit_total_over(self, rule):
        return f"total over ${rule.amount}"

    def visit_has(self, rule):
        return f"has a {rule.kind}"

    def visit_and(self, rule):
        return f"{self.part(rule.left)} and {self.part(rule.right)}"

    def visit_or(self, rule):
        return f"{self.part(rule.left)} or {self.part(rule.right)}"

    def visit_not(self, rule):
        return f"not {self.part(rule.rule)}"

    def part(self, rule):
        """An "and" or an "or" inside another piece gets brackets, so the words read the right way."""
        text = rule.accept(self)
        return f"({text})" if isinstance(rule, (And, Or)) else text


class Counter:
    def visit_total_over(self, rule):
        return 1

    def visit_has(self, rule):
        return 1

    def visit_and(self, rule):
        return 1 + rule.left.accept(self) + rule.right.accept(self)

    def visit_or(self, rule):
        return 1 + rule.left.accept(self) + rule.right.accept(self)

    def visit_not(self, rule):
        return 1 + rule.rule.accept(self)


class KindChecker:
    """The new job: no piece class changed to add it."""
    SOLD = ["shoe", "jacket", "bottle", "socks"]

    def visit_total_over(self, rule):
        return []

    def visit_has(self, rule):
        return [] if rule.kind in self.SOLD else [f'the store sells no "{rule.kind}"']

    def visit_and(self, rule):
        return rule.left.accept(self) + rule.right.accept(self)

    def visit_or(self, rule):
        return rule.left.accept(self) + rule.right.accept(self)

    def visit_not(self, rule):
        return rule.rule.accept(self)


rules = {
    "TRAIL10": And(TotalOver(50), Or(Has("shoe"), Has("jacket"))),
    "BOTTLE": And(Has("jacket"), Not(Has("bottle"))),
    "SUMMIT15": And(Has("boot"), TotalOver(100)),
}
for code, rule in rules.items():
    problems = rule.accept(KindChecker())
    print(f"{code}: {rule.accept(Describer())}")
    print(f"  {rule.accept(Counter())} pieces, {', '.join(problems) or 'no problems'}")
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```javascript
// Each piece only knows how to hand itself to a visitor.
class TotalOver {
  constructor(amount) { this.amount = amount; }
  accept(visitor) { return visitor.visitTotalOver(this); }
}

class Has {
  constructor(kind) { this.kind = kind; }
  accept(visitor) { return visitor.visitHas(this); }
}

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

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

class Not {
  constructor(rule) { this.rule = rule; }
  accept(visitor) { return visitor.visitNot(this); }
}

// A visitor is one job, with a method for each kind of piece.
class Describer {
  visitTotalOver(rule) { return `total over $${rule.amount}`; }
  visitHas(rule) { return `has a ${rule.kind}`; }
  visitAnd(rule) { return `${this.part(rule.left)} and ${this.part(rule.right)}`; }
  visitOr(rule) { return `${this.part(rule.left)} or ${this.part(rule.right)}`; }
  visitNot(rule) { return `not ${this.part(rule.rule)}`; }

  // An "and" or an "or" inside another piece gets brackets, so the words read the right way.
  part(rule) {
    return rule instanceof And || rule instanceof Or ? `(${rule.accept(this)})` : rule.accept(this);
  }
}

class Counter {
  visitTotalOver(rule) { return 1; }
  visitHas(rule) { return 1; }
  visitAnd(rule) { return 1 + rule.left.accept(this) + rule.right.accept(this); }
  visitOr(rule) { return 1 + rule.left.accept(this) + rule.right.accept(this); }
  visitNot(rule) { return 1 + rule.rule.accept(this); }
}

// The new job: no piece class changed to add it.
class KindChecker {
  static sold = ["shoe", "jacket", "bottle", "socks"];

  visitTotalOver(rule) { return []; }
  visitHas(rule) { return KindChecker.sold.includes(rule.kind) ? [] : [`the store sells no "${rule.kind}"`]; }
  visitAnd(rule) { return [...rule.left.accept(this), ...rule.right.accept(this)]; }
  visitOr(rule) { return [...rule.left.accept(this), ...rule.right.accept(this)]; }
  visitNot(rule) { return rule.rule.accept(this); }
}

const rules = new Map([
  ["TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")))],
  ["BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle")))],
  ["SUMMIT15", new And(new Has("boot"), new TotalOver(100))],
]);
for (const [code, rule] of rules) {
  const problems = rule.accept(new KindChecker());
  console.log(`${code}: ${rule.accept(new Describer())}`);
  console.log(`  ${rule.accept(new Counter())} pieces, ${problems.join(", ") || "no problems"}`);
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```typescript
// Each piece only knows how to hand itself to a visitor.
interface Rule {
  accept<T>(visitor: RuleVisitor<T>): T;
}

class TotalOver implements Rule {
  amount: number;
  constructor(amount: number) { this.amount = amount; }
  accept<T>(visitor: RuleVisitor<T>): T { return visitor.visitTotalOver(this); }
}

class Has implements Rule {
  kind: string;
  constructor(kind: string) { this.kind = kind; }
  accept<T>(visitor: RuleVisitor<T>): T { return visitor.visitHas(this); }
}

class And implements Rule {
  left: Rule;
  right: Rule;
  constructor(left: Rule, right: Rule) { this.left = left; this.right = right; }
  accept<T>(visitor: RuleVisitor<T>): T { return visitor.visitAnd(this); }
}

class Or implements Rule {
  left: Rule;
  right: Rule;
  constructor(left: Rule, right: Rule) { this.left = left; this.right = right; }
  accept<T>(visitor: RuleVisitor<T>): T { return visitor.visitOr(this); }
}

class Not implements Rule {
  rule: Rule;
  constructor(rule: Rule) { this.rule = rule; }
  accept<T>(visitor: RuleVisitor<T>): T { return visitor.visitNot(this); }
}

// A visitor is one job, with a method for each kind of piece.
interface RuleVisitor<T> {
  visitTotalOver(rule: TotalOver): T;
  visitHas(rule: Has): T;
  visitAnd(rule: And): T;
  visitOr(rule: Or): T;
  visitNot(rule: Not): T;
}

class Describer implements RuleVisitor<string> {
  visitTotalOver(rule: TotalOver): string { return `total over $${rule.amount}`; }
  visitHas(rule: Has): string { return `has a ${rule.kind}`; }
  visitAnd(rule: And): string { return `${this.part(rule.left)} and ${this.part(rule.right)}`; }
  visitOr(rule: Or): string { return `${this.part(rule.left)} or ${this.part(rule.right)}`; }
  visitNot(rule: Not): string { return `not ${this.part(rule.rule)}`; }

  // An "and" or an "or" inside another piece gets brackets, so the words read the right way.
  part(rule: Rule): string {
    return rule instanceof And || rule instanceof Or ? `(${rule.accept(this)})` : rule.accept(this);
  }
}

class Counter implements RuleVisitor<number> {
  visitTotalOver(rule: TotalOver): number { return 1; }
  visitHas(rule: Has): number { return 1; }
  visitAnd(rule: And): number { return 1 + rule.left.accept(this) + rule.right.accept(this); }
  visitOr(rule: Or): number { return 1 + rule.left.accept(this) + rule.right.accept(this); }
  visitNot(rule: Not): number { return 1 + rule.rule.accept(this); }
}

// The new job: no piece class changed to add it.
class KindChecker implements RuleVisitor<string[]> {
  static sold = ["shoe", "jacket", "bottle", "socks"];

  visitTotalOver(rule: TotalOver): string[] { return []; }
  visitHas(rule: Has): string[] { return KindChecker.sold.includes(rule.kind) ? [] : [`the store sells no "${rule.kind}"`]; }
  visitAnd(rule: And): string[] { return [...rule.left.accept(this), ...rule.right.accept(this)]; }
  visitOr(rule: Or): string[] { return [...rule.left.accept(this), ...rule.right.accept(this)]; }
  visitNot(rule: Not): string[] { return rule.rule.accept(this); }
}

const rules = new Map<string, Rule>([
  ["TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket")))],
  ["BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle")))],
  ["SUMMIT15", new And(new Has("boot"), new TotalOver(100))],
]);
for (const [code, rule] of rules) {
  const problems = rule.accept(new KindChecker());
  console.log(`${code}: ${rule.accept(new Describer())}`);
  console.log(`  ${rule.accept(new Counter())} pieces, ${problems.join(", ") || "no problems"}`);
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

The checker found SUMMIT15's "boot", and no piece class changed to add it. Next month's job is one new class with five methods, and the pieces don't change.

Here is the trick that makes it work. `rule.accept(new Describer())` makes two choices with two calls. The first call, `accept`, runs the code for the piece's own kind (here, an "and"). Inside it, `visitor.VisitAnd(this)` runs the code for the visitor's job (describing). Picking code by two things, the kind of piece *and* the kind of job, is called **double dispatch**, and it's why every piece needs its one-line `accept`.

C#, Java and TypeScript give the visitor a generic type, `IRuleVisitor<T>`, so each job hands back its own kind of answer: words, a number, a list of problems. Python and JavaScript need no interface: any object with the five `visit` methods is a visitor.

Here are the three jobs visiting one tree, TRAIL10:

![One TRAIL10 tree, the same "and", "or" and three checks, drawn three times, each visited by a different job that writes its answer above it: describe writes "total over $50 and (has a shoe or has a jacket)", count writes "5 pieces", and check writes "no problems"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/e835c7215e154981b5988b305a59c20f.webp)

## How it got its name

Teams writing compilers and code checkers kept meeting this exact problem: a family of pieces that hardly ever changed (the parts of a programming language) and a list of jobs that never stopped growing (check the types, format the code, find unused variables). They kept landing on the same fix, and the 1994 book of patterns called it the **Visitor pattern**: the job *visits* each piece. It's the **open/closed principle** applied to jobs: the tree is open to new jobs and closed to edits. It's a trade, though: a new kind of piece needs a new method in every visitor.

## The modern version: pattern matching

Today's languages can look at a value and pick a case by its kind, with `switch` or `match`. Then a job is one function with a case for each kind of piece, and the pieces can be plain data:

```csharp
Dictionary<string, IRule> rules = new Dictionary<string, IRule>
{
    ["TRAIL10"] = new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))),
    ["BOTTLE"] = new And(new Has("jacket"), new Not(new Has("bottle"))),
    ["SUMMIT15"] = new And(new Has("boot"), new TotalOver(100)),
};
foreach (KeyValuePair<string, IRule> rule in rules)
{
    List<string> problems = Check(rule.Value);
    Console.WriteLine($"{rule.Key}: {Describe(rule.Value)}");
    Console.WriteLine($"  {Count(rule.Value)} pieces, {(problems.Count > 0 ? string.Join(", ", problems) : "no problems")}");
}

// Each job is one function with a case for each kind of piece.
string Describe(IRule rule) => rule switch
{
    TotalOver total => $"total over ${total.Amount}",
    Has has => $"has a {has.Kind}",
    And both => $"{Part(both.Left)} and {Part(both.Right)}",
    Or either => $"{Part(either.Left)} or {Part(either.Right)}",
    Not negation => $"not {Part(negation.Rule)}",
    _ => throw new ArgumentException("A piece Describe doesn't know"),
};

// An "and" or an "or" inside another piece gets brackets, so the words read the right way.
string Part(IRule rule) => rule is And or Or ? $"({Describe(rule)})" : Describe(rule);

int Count(IRule rule) => rule switch
{
    And both => 1 + Count(both.Left) + Count(both.Right),
    Or either => 1 + Count(either.Left) + Count(either.Right),
    Not negation => 1 + Count(negation.Rule),
    _ => 1,
};

List<string> Check(IRule rule) => rule switch
{
    Has has when !new[] { "shoe", "jacket", "bottle", "socks" }.Contains(has.Kind) => new List<string> { $"the store sells no \"{has.Kind}\"" },
    And both => Check(both.Left).Concat(Check(both.Right)).ToList(),
    Or either => Check(either.Left).Concat(Check(either.Right)).ToList(),
    Not negation => Check(negation.Rule),
    _ => new List<string>(),
};

// The pieces are plain data now: no methods at all.
interface IRule;
record TotalOver(int Amount) : IRule;
record Has(string Kind) : IRule;
record And(IRule Left, IRule Right) : IRule;
record Or(IRule Left, IRule Right) : IRule;
record Not(IRule Rule) : IRule;
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```java
// The pieces are plain data now: no methods at all. "sealed" lists every kind there is.
sealed interface Rule permits TotalOver, Has, And, Or, Not {}
record TotalOver(int amount) implements Rule {}
record Has(String kind) implements Rule {}
record And(Rule left, Rule right) implements Rule {}
record Or(Rule left, Rule right) implements Rule {}
record Not(Rule rule) implements Rule {}

// Each job is one method with a case for each kind of piece.
String describe(Rule rule) {
    return switch (rule) {
        case TotalOver(int amount) -> "total over $" + amount;
        case Has(String kind) -> "has a " + kind;
        case And(Rule left, Rule right) -> part(left) + " and " + part(right);
        case Or(Rule left, Rule right) -> part(left) + " or " + part(right);
        case Not(Rule inner) -> "not " + part(inner);
    };
}

// An "and" or an "or" inside another piece gets brackets, so the words read the right way.
String part(Rule rule) {
    return rule instanceof And || rule instanceof Or ? "(" + describe(rule) + ")" : describe(rule);
}

int count(Rule rule) {
    return switch (rule) {
        case And(Rule left, Rule right) -> 1 + count(left) + count(right);
        case Or(Rule left, Rule right) -> 1 + count(left) + count(right);
        case Not(Rule inner) -> 1 + count(inner);
        case TotalOver total -> 1;
        case Has has -> 1;
    };
}

List<String> check(Rule rule) {
    return switch (rule) {
        case Has(String kind) when !List.of("shoe", "jacket", "bottle", "socks").contains(kind) -> List.of("the store sells no \"" + kind + "\"");
        case And(Rule left, Rule right) -> Stream.concat(check(left).stream(), check(right).stream()).toList();
        case Or(Rule left, Rule right) -> Stream.concat(check(left).stream(), check(right).stream()).toList();
        case Not(Rule inner) -> check(inner);
        case Has has -> List.of();
        case TotalOver total -> List.of();
    };
}

void main() {
    Map<String, Rule> rules = new LinkedHashMap<>();
    rules.put("TRAIL10", new And(new TotalOver(50), new Or(new Has("shoe"), new Has("jacket"))));
    rules.put("BOTTLE", new And(new Has("jacket"), new Not(new Has("bottle"))));
    rules.put("SUMMIT15", new And(new Has("boot"), new TotalOver(100)));
    for (String code : rules.keySet()) {
        Rule rule = rules.get(code);
        List<String> problems = check(rule);
        IO.println(code + ": " + describe(rule));
        IO.println("  " + count(rule) + " pieces, " + (problems.isEmpty() ? "no problems" : String.join(", ", problems)));
    }
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```python
from dataclasses import dataclass


# The pieces are plain data now: no methods at all.
@dataclass
class TotalOver:
    amount: int


@dataclass
class Has:
    kind: str


@dataclass
class And:
    left: object
    right: object


@dataclass
class Or:
    left: object
    right: object


@dataclass
class Not:
    rule: object


# Each job is one function with a case for each kind of piece.
def describe(rule):
    match rule:
        case TotalOver(amount):
            return f"total over ${amount}"
        case Has(kind):
            return f"has a {kind}"
        case And(left, right):
            return f"{part(left)} and {part(right)}"
        case Or(left, right):
            return f"{part(left)} or {part(right)}"
        case Not(inner):
            return f"not {part(inner)}"


def part(rule):
    """An "and" or an "or" inside another piece gets brackets, so the words read the right way."""
    return f"({describe(rule)})" if isinstance(rule, (And, Or)) else describe(rule)


def count(rule):
    match rule:
        case And(left, right) | Or(left, right):
            return 1 + count(left) + count(right)
        case Not(inner):
            return 1 + count(inner)
        case _:
            return 1


def check(rule):
    match rule:
        case Has(kind) if kind not in ["shoe", "jacket", "bottle", "socks"]:
            return [f'the store sells no "{kind}"']
        case And(left, right) | Or(left, right):
            return check(left) + check(right)
        case Not(inner):
            return check(inner)
        case _:
            return []


rules = {
    "TRAIL10": And(TotalOver(50), Or(Has("shoe"), Has("jacket"))),
    "BOTTLE": And(Has("jacket"), Not(Has("bottle"))),
    "SUMMIT15": And(Has("boot"), TotalOver(100)),
}
for code, rule in rules.items():
    problems = check(rule)
    print(f"{code}: {describe(rule)}")
    print(f"  {count(rule)} pieces, {', '.join(problems) or 'no problems'}")
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```javascript
// The pieces are plain data now: objects with a "type" that says which kind of piece they are.
const totalOver = (amount) => ({ type: "totalOver", amount });
const has = (kind) => ({ type: "has", kind });
const and = (left, right) => ({ type: "and", left, right });
const or = (left, right) => ({ type: "or", left, right });
const not = (rule) => ({ type: "not", rule });

// Each job is one function with a case for each kind of piece.
function describe(rule) {
  switch (rule.type) {
    case "totalOver": return `total over $${rule.amount}`;
    case "has": return `has a ${rule.kind}`;
    case "and": return `${part(rule.left)} and ${part(rule.right)}`;
    case "or": return `${part(rule.left)} or ${part(rule.right)}`;
    case "not": return `not ${part(rule.rule)}`;
    default: throw new Error(`A piece describe doesn't know: ${rule.type}`);
  }
}

// An "and" or an "or" inside another piece gets brackets, so the words read the right way.
function part(rule) {
  return rule.type === "and" || rule.type === "or" ? `(${describe(rule)})` : describe(rule);
}

function count(rule) {
  switch (rule.type) {
    case "and":
    case "or": return 1 + count(rule.left) + count(rule.right);
    case "not": return 1 + count(rule.rule);
    default: return 1;
  }
}

function check(rule) {
  switch (rule.type) {
    case "has": return ["shoe", "jacket", "bottle", "socks"].includes(rule.kind) ? [] : [`the store sells no "${rule.kind}"`];
    case "and":
    case "or": return [...check(rule.left), ...check(rule.right)];
    case "not": return check(rule.rule);
    default: return [];
  }
}

const rules = new Map([
  ["TRAIL10", and(totalOver(50), or(has("shoe"), has("jacket")))],
  ["BOTTLE", and(has("jacket"), not(has("bottle")))],
  ["SUMMIT15", and(has("boot"), totalOver(100))],
]);
for (const [code, rule] of rules) {
  const problems = check(rule);
  console.log(`${code}: ${describe(rule)}`);
  console.log(`  ${count(rule)} pieces, ${problems.join(", ") || "no problems"}`);
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

```typescript
// The pieces are plain data now: a union type, where "type" says which kind of piece it is.
type Rule =
  | { type: "totalOver"; amount: number }
  | { type: "has"; kind: string }
  | { type: "and"; left: Rule; right: Rule }
  | { type: "or"; left: Rule; right: Rule }
  | { type: "not"; rule: Rule };

const totalOver = (amount: number): Rule => ({ type: "totalOver", amount });
const has = (kind: string): Rule => ({ type: "has", kind });
const and = (left: Rule, right: Rule): Rule => ({ type: "and", left, right });
const or = (left: Rule, right: Rule): Rule => ({ type: "or", left, right });
const not = (rule: Rule): Rule => ({ type: "not", rule });

// Each job is one function with a case for each kind of piece.
function describe(rule: Rule): string {
  switch (rule.type) {
    case "totalOver": return `total over $${rule.amount}`;
    case "has": return `has a ${rule.kind}`;
    case "and": return `${part(rule.left)} and ${part(rule.right)}`;
    case "or": return `${part(rule.left)} or ${part(rule.right)}`;
    case "not": return `not ${part(rule.rule)}`;
  }
}

// An "and" or an "or" inside another piece gets brackets, so the words read the right way.
function part(rule: Rule): string {
  return rule.type === "and" || rule.type === "or" ? `(${describe(rule)})` : describe(rule);
}

function count(rule: Rule): number {
  switch (rule.type) {
    case "and":
    case "or": return 1 + count(rule.left) + count(rule.right);
    case "not": return 1 + count(rule.rule);
    default: return 1;
  }
}

function check(rule: Rule): string[] {
  switch (rule.type) {
    case "has": return ["shoe", "jacket", "bottle", "socks"].includes(rule.kind) ? [] : [`the store sells no "${rule.kind}"`];
    case "and":
    case "or": return [...check(rule.left), ...check(rule.right)];
    case "not": return check(rule.rule);
    default: return [];
  }
}

const rules = new Map<string, Rule>([
  ["TRAIL10", and(totalOver(50), or(has("shoe"), has("jacket")))],
  ["BOTTLE", and(has("jacket"), not(has("bottle")))],
  ["SUMMIT15", and(has("boot"), totalOver(100))],
]);
for (const [code, rule] of rules) {
  const problems = check(rule);
  console.log(`${code}: ${describe(rule)}`);
  console.log(`  ${count(rule)} pieces, ${problems.join(", ") || "no problems"}`);
}
```

```text
TRAIL10: total over $50 and (has a shoe or has a jacket)
  5 pieces, no problems
BOTTLE: has a jacket and not has a bottle
  4 pieces, no problems
SUMMIT15: has a boot and total over $100
  3 pieces, the store sells no "boot"
```

This is the second try from *What would you try?*, now with help. In Java, `sealed` lists every kind of piece, so the compiler refuses a `switch` that forgets one; TypeScript's union type does the same for `describe`. C# can't be sure an interface has only five kinds, so its `switch` needs a last `_` case, and Python's `match` doesn't check either: there, remembering every kind is up to you. It's how most new code does Visitor's job, with the same trade: a new job is easy, and a new kind of piece means a new case in every function.

## Where you've already used it

- **Java's `Files.walkFileTree(folder, visitor)`** walks every folder and file and calls the visitor's `visitFile` and `preVisitDirectory` methods.
- **Python's `ast.NodeVisitor`:** you write `visit_FunctionDef` and `visit_Call`, and it calls them for each part of a Python program. Code checkers are built this way.
- **ESLint rules and Babel plugins** are visitors: objects with a method for each kind of code, such as `CallExpression(node) { … }`.
- **C#'s Roslyn analyzers** use a `CSharpSyntaxWalker` with methods like `VisitMethodDeclaration`.

## When not to use it

- **When new kinds of piece arrive often.** Each one means a new method in every visitor. Then a method in each class is the better trade.
- **When there are only one or two jobs.** A method in each class is easier to read than `accept` and `visit` bouncing back and forth.
- **When the pieces should keep their insides private.** A visitor can only do its job if every piece shows what it holds (the amount, the kind, the left and right pieces).

That's why it's rarely the first answer: in most code, new kinds turn up more often than new jobs, and the double jump is harder to follow than one method call.

**How often you'll meet it:** rarely in business apps, and now and then in tools (our estimate: it's everywhere inside compilers, code checkers and editors; in everyday app code, pattern matching usually does the job).

## Check yourself

2 questions to try on the lesson page.

## So what

When the kinds of thing stay put and the jobs keep coming, put each job in one place, as a visitor or a `switch` the compiler checks, and the family never has to change for it. When the kinds keep coming instead, keep the method in each class.

## Key terms

- [Visitor Pattern](https://www.ask-codey.com/glossary/visitor-pattern)
- [Double Dispatch](https://www.ask-codey.com/glossary/double-dispatch)
- [Open/Closed Principle](https://www.ask-codey.com/glossary/open-closed-principle)

## Cheat sheets

- [Visitor: New Jobs Without Touching Every Class](https://www.ask-codey.com/cheat-sheets/dp-visitor-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-visitor
