Fluent Visitors: revisiting a classic design pattern
Posted by neilmadden@reddit | programming | View on Reddit | 2 comments
Posted by neilmadden@reddit | programming | View on Reddit | 2 comments
WorldsBegin@reddit
The visitor pattern is useful in a language that doesn't have pattern matching. Once you can pattern match natively, its usecases go way down. All the examples in the post are most readable (to me) in the first form given that has explicit recursive calls and one match statement.
In "Benefits of encapsulation" we can see the same visitor being used on a different representation of the data, but the tradeoff should be made clearer. With the visitor pattern you commit to a specific (bottom up) evaluation order. You must produce arguments that the visitor produces for subtrees, even if these are not used. You can't simply "skip" a subtree as shown, which the pattern matching approach allows naturally. Note that in the "reverse polish notation", this evaluation order also naturally follows from the representation and you'd need to preprocess the expression to support skipping, so it's a perfect fit there.
neilmadden@reddit (OP)
The “it’s just pattern matching” objection is explicitly addressed in the last section.
Control over traversal order or skipping nodes can easily be accommodated if needed (eg allow the visitor to return a control code).