From: Caleb Clausen Date: 2010-04-28T02:45:08+09:00 Subject: Re: Visitor pattern On 4/27/10, Bernhard Brodowsky wrote: > Hi, > I heard many times that the visitor pattern is useless in Ruby and > similar things. > However, I'm just writing an interpreter for a small imperative > language. I finished the parser and am just beginning to think about how > to implement the interpreter. > I just thought that it's a perfect place to use the visitor pattern, the > abstract syntax tree is the object structure to be "visited" and the > interpreter is a visitor. > This would have another advantage, namely that I can easily add more > visitors, like for example a pretty printer or something to compare ASTs > (useful for unit tests) > I could just add this functionality to the elements of the AST directly, > but somehow, I don't like this because I always have to search my ~30 > classes that represent syntax units and implement one method in each of > them. Instead, it's much more comfortable to just write one new class. > > What do you think about that? Is it really that bad to use the visitor > pattern in Ruby? And if yes, what is the reason for this? Personally, I prefer to write 30 different SyntaxNode#visit methods (or whatever you call them). But it's really a matter of taste. If you create an actual visitor class (or method), I think you'll find at the core of it a big ugly case statement. I like case statements more than most people, but when they get bigger than a page, I get nervous. (The ideal solution would be to have a set of pattern-matching rules and actions to be taken when those patterns are found in the tree. The patterns would be more complicated than simply node classes; they could depend on properties of the nodes. This starts to look a lot like haskell or maybe antlr. I've tried hard to get this to work in ruby, and successfully done the pattern-matching part but getting actions to work as well turned out to be surprisingly difficult. AFAIK, no one else has done any better.)