Hacker News new | ask | show | jobs
by grandinj 2662 days ago
The thing that annoys me most about this pattern is that people always miss the "there needs to be lots of things you want to perform on those thingies".

And so we end up with a huge pile of visitor code, and there is one or maybe two actual visitors.

When it would have been far easier to read and modify if it was just coded out normally.

3 comments

I’ve never considered this, but I think it’s a fair assessment! It’s particularly striking when you see a compiler with multiple visitors that are refactored into one or two visitors to reduce the number of traversals. I think I understand the cause, it’s easier to start with a visitor pattern than refactoring into a visitor pattern.

Nevertheless, for many problems, like compiler construction, I’ve never seen a pattern that matched the utility of the visitor (even outside of imperative and object-oriented patterns)

Use the right language: one with ML style pattern matching.
check out multi-methods and multiple-dispatch OO
IMHO, the most important condition is the need to do different stuff on different (small) subsets of classes, typically combined with a (non-trivial) tree traversal. Otherwise, its more straightforward to add regular virtual methods.
Or in this case, since the IThingyInteractor can do exactly the same thing with an IThingy if IThingy has a name() method, you can just implement it with single dispatch.

I don't know if I have ever actually seen a true implementation of this pattern. What I have seen is a pattern someone called a Visitor where a tree is iterated over and the "Visitor" makes virtual function calls on the composite node in a single function body without ever doing something different depending on the type of the node.