←back to thread

1087 points smartmic | 2 comments | | HN request time: 0.413s | source
Show context
12_throw_away ◴[] No.44303909[source]
This has by far the best discussion of the visitor pattern I've yet to come across.
replies(3): >>44304154 #>>44304309 #>>44304662 #
ahartmetz ◴[] No.44304662[source]
I care about naming, and I find the name of the visitor pattern infuriatingly bad. Very clubbable. I think I have never created one called "Visitor" in my life.

Given the syntax tree example from Wikipedia, I think I'd call it AstWalker, AstItem::dispatch(AstWalker) and AstWalker::process(AstItem) instead of Visitor, AstItem::accept(AstVisitor) and AstVisitor::visit(AstItem).

"The walker walks the AST, each items sends it to the next ones, and the walker processes them". That means something. "The visitor visits the AST items, which accept it" means basically nothing. It's more general, but also contains very little useful information. So the visitor might need different names in different situations. Fine. Just add a comment "visitor pattern" for recognizability.

I remember a situation where I needed to walk two object trees for a data comparison and import operation. I created an AbstractImporter that walked the two trees in lockstep in a guaranteed order and invoked virtual methods for each difference. It had a non-virtual doImport() for the ordered data walk, and doImport() called virtual methods like importUserAccount(), importUserAccountGrouMemberships() etc. There were two subclasses of AbstractImporter: ImportAnalyzer collected differences to display them, then there was a selection step implemented by a kind of list model + a bit of controller logic, then an ImportWorker to make the selected changes. All rather specific terminology and not exactly the visitor pattern.

replies(1): >>44316701 #
1. zelphirkalt ◴[] No.44316701[source]
But the idea of the visitor pattern is not, that it itself walks a tree. The idea is, that it doesn't know how to walk the tree and will be passed in elements from the tree, to its visit method. It does only need to know what to do with one element at a time. The walking is implemented elsewhere.
replies(1): >>44323858 #
2. ahartmetz ◴[] No.44323858[source]
One may pretend that it's not the case, but in practice, the visitor/walker does traverse the tree in a particular, systematic order. Walker implies a somewhat systematic traversal (I think), which is what it does. As the implementor of its visit() methods, it doesn't even matter whether the generic Visitor class chooses the path or the nodes do. Visitor is also super vague. Does it just say "Hi" to the whole tree and then leave? Does it only visit the museums and ignore the parks?