Course contentsShow
← Software Engineering
Lesson 320 of 1,9339. Behavioral Design PatternsFree lesson

When Visitor Adds vs Removes Flexibility

Recognize when Visitor makes adding operations easy but types hard, versus when simpler approaches maintain better flexibility.

When Visitor Adds vs Removes Flexibility

What you'll learn: You'll understand the specific scenarios where Visitor helps versus where it creates unnecessary rigidity.

The Flexibility Paradox

The Visitor pattern presents an interesting trade-off: it makes adding new operations trivial but makes adding new types painful. Understanding when this trade-off favors you determines whether Visitor is the right choice.

When Visitor Adds Flexibility

Visitor shines when:

  • Your type hierarchy is stable — you have a fixed set of classes (like AST nodes in a compiler: IfNode, WhileNode, AssignmentNode) that rarely change
  • You frequently add new operations — new analyses, transformations, or reports on the same structure
  • Operations don't belong in the classes themselves — adding syntax highlighting, optimization passes, or code generation to your AST nodes would bloat them

In these cases, Visitor lets you add operations without touching existing code. Each new visitor is a self-contained module.

When Visitor Removes Flexibility

Visitor becomes a burden when:

  • Your type hierarchy changes often — adding a new type means updating every single visitor with a new visit method
  • You have few operations — if you only have 2-3 operations, putting them directly in the classes via polymorphism is simpler
  • Operations naturally belong in the classes — if drawing a shape is its primary purpose, shape.draw() is clearer than DrawVisitor

The double dispatch mechanism that makes Visitor work also couples all visitors to the complete type hierarchy. One new type breaks all visitors until updated.

Key Takeaway: Use Visitor when your types are stable but operations grow; avoid it when your type hierarchy evolves frequently or when simpler polymorphism suffices. The pattern exchanges flexibility in one dimension (types) for flexibility in another (operations).