Visitor pattern revisited in D

OOP is known (or should be known) as a behavioral abstraction. It nicely solves a vast variety of problems, but enforces on the programmer an abstraction that doesn’t fit every problem. The fact is, you sometime need objects as data abstractions and not behavioral abstractions.

This is commonly the case for tools that manipulate code. A parser typically returns an AST that will be processed. The processing can be compilation, code formating, code analysis, and basically any other use related to source code manipulation.

Following regular OOP principles, manipulations have to be implemented by the AST node classes. This is a problem, because it prevents any 3rd party developer tool to reuse an existing parser and AST. The known solution is to use the Visitor pattern, which allows to dispatch in our code according to the AST node’s type.

The Visitor pattern has many known problems, to the point that many consider it an antipattern. A better solution using D has to be proposed.

Continue reading