Hacker News new | ask | show | jobs
by hathawsh 2662 days ago
The visitor pattern isn't appropriate everywhere, but it's quite good for traversing and manipulating ASTs (abstract syntax trees). An AST typically has many kinds of nodes, but programs that traverse the AST usually only care about some small subset of those nodes. The visitor pattern provides a clean solution: a generic AST traversal library visits all nodes in the tree while allowing the program to customize what happens when visiting specific nodes. I've found the visitor pattern very effective for creating derivative ASTs without knowing about everything that might be in the AST.
2 comments

Yes, this is the only place I have ever used the visitor / double dispatch pattern. The main idea is it fulfills the "Open-Closed" principle:

https://en.wikipedia.org/wiki/Open–closed_principle

Otherwise you find that your AST data structure is never finished -- you are constantly added stuff to it. I wish there was a clearer way in C++, but this is the C++ solution.

But often a pattern matching switch expression would be nicer, if your language has such a thing.