2 ms·
Yes, that description of the visitor pattern seems wrong to me. The visitor pattern isn't about operating on the elements of collections, it's about altering be
by voyou 11y ago
Yes, that description of the visitor pattern seems wrong to me. The visitor pattern isn't about operating on the elements of collections, it's about altering behavior depending on the type of object being operated on.
- vidarh 11y agoThe point is that in a statically typed language, the specific approach advocated by the visitor pattern gets compiler assistance to ensure the visitors are complete (at least in the sense that there is a visit() method for each node type). This coupled with limited, difficult to use, or expensive runtime type information in many static languages made it attractive. In a dynamically typed language where checking if an object is of a specific class, and where you can do if-then or switch(case/when) to discriminate the node types easily, the visitor pattern kind-of devolves into pretty much nothing, and hence the description doesn't "sound" right because it misses out on most of what makes the Visitor pattern worthwhile to discuss as a pattern in e.g. C++ or Java. Instead of e.g. implementing an "accept" method for each node that calls "visit" on a visitor, and implementing a "Visitor" interface and inheriting from that, in Ruby you might instead just opt to use a case/when structure for the visitor, and wrap it in a single method or a lambda if you need to pass it around.
- hnov 11y agoMore generally, the visitor pattern is an example of double dispatch, where the concrete implementation of a function varies on the type of two parameters to the function. I'm not sure that there's any real difference in the implementation of the visitor pattern that arises from static vs dynamic typing. Just like in ruby, in a language like java you could have a cascade of if/elses that type check the second parameter (or the first one for that matter, OO is really just a way to have a case statement that isn't centralized in one place in source code).
- vidarh 11y agoBut in the GoF visitor pattern, the "case statement" is in fact centralized in one place: In the class implementing the visitor. And of course you can have the equivalent in C++/Java and similar languages, but that would lose the main benefit of having the completeness of the visitor statically checked (In other words, you can write dynamically typed code in any language some way or the).