# Visitor

> The Visitor design pattern allows adding further operations to objects of a class, without modifying the classes themselves.

## What is the Visitor design pattern?

The design pattern that allows new operations to be added to existing object structures without modifying the objects themselves. It centralizes operations in a separate visitor class and promotes the Open-Closed principle.

- Topic: Behavioral Patterns
- Type: design pattern

## Example

Wrong:

```js
class Circle {
  area() { return Math.PI * this.r ** 2; }
  toSvg() { /* ... */ }
  toJson() { /* ... */ }
}
```

Right:

```js
const areaVisitor = {
  circle: (s) => Math.PI * s.r ** 2,
  rect: (s) => s.w * s.h,
};

const visit = (shape, visitor) => visitor[shape.kind](shape);
visit({ kind: 'rect', w: 2, h: 3 }, areaVisitor);
```

Each operation lives in its own visitor keyed by node type, so shapes stay unchanged as new operations are added.

## Common mistakes

- Adding a method to every class for each new operation.
- A visitor that silently ignores node types it doesn't know.

## Key points

- The visitor has a handler for every node type, and an unknown type throws instead of being skipped silently.
- New operations are added as new visitors without editing the node classes.
- In TypeScript, node types form a discriminated union so a missing handler is a type error.

## Interview questions

### Where is the Visitor pattern used in practice?

Compilers, linters and code transformers walk syntax trees with visitors that have one handler per node type.

### What is the downside of the Visitor pattern?

Adding a new node type is hard: every existing visitor must get a new handler. It suits stable structures with frequently added operations.

### What is double dispatch in Visitor?

The node calls `visitor.visitX(this)` from its `accept` method, so the chosen code depends on both the node type and the visitor type.

## Related cards

- [Composite](https://wonderium.dev/engineering/composite.md)
- [Open-Closed](https://wonderium.dev/engineering/open-closed.md)
- [Tree](https://wonderium.dev/algorithms/tree.md)
- [Static Code Analysis](https://wonderium.dev/engineering/static-code-analysis.md)
- [Union Type](https://wonderium.dev/ts/union-type.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/visitor
- Last updated: 2026-11-25
