Search code examples
javadesign-patternstraversalvisitor-pattern

When do you decide to use a visitors for your objects?


I always thought an object needs the data and the messages to act on it. When would you want a method that is extrinsic to the object? What rule of thumb do you follow to have a visitor? This is supposing that you have full control of the object graph.


Solution

  • I always thought an object needs the data and the messages to act on it. When would you want a method that is extrinsic to the object? What rule of thumb do you follow to have a visitor? This is supposing that you have full control of the object graph.

    It's sometimes not convenient to have all behaviors for a particular object defined in one class. For instance in Java, if your module requires a method toXml to be implemented in a bunch of classes originally defined in another module, it's complicated because you can not write toXml somewhere else than the original class file, which mean you can not extend the system without changing existing sources (in Smalltalk or other languages, you can group method in extension which are not tied to a particular file).

    More generally, there's a tension in statically typed languages between the ability to (1) add new functions to existing data types, and (2) add new data types implementations supporting the same functions -- that's called the expression problem (wikipedia page).

    Object oriented languages excel at point 2. If you have an interface, you can add new implementations safely and easily. Functional languages excel at point 1. They rely on pattern matching/ad-hoc polymorphism/overloading so you can add new functions to existing types easily.

    The visitor pattern is a way to support point 1 in an object-oriented design: you can easily extend the system with new behaviors in a type-safe way (which wouldn't be the case if you do kind of manual pattern matching with if-else-instanceof because the language would never warn you if a case is not covered).

    Visitors are then typically used when there is a fixed set of known types, which I think is what you meant by "full control of the object graph". Examples include token in a parser, tree with various types of nodes, and similar situations.

    So to conclude, I would say you were right in your analysis :)

    PS: The visitor pattern works well with the composite pattern, but they are also useful individually