Visitors Galore
My Advisor, Dr. Mayer Goldberg, claims that object-oriented programming is like functional programming, only with named arguments. Objects are closures. Constructors are lambdas. Invoking a method is applying the closure. That’s it.
I faced a good demonstrations of that claim while I was working on a small code generator. I wanted to exploit Java’s annotation processing, so I can make this generator a part of a build process. The annotation processing mechanism uses the visitor design pattern extensively. By “extensively” I actually mean “you cannot get a concrete value without using at least two visitors”. These visitors are:
- Element visitor: Since Java code is composed of packages, classes, methods and so on, you need a visitor to tell you which kind of element you are currenly holding.
- Type visitors: A type in Java can be a declared type (class, interface, etc.), an array type, primitive type and so forth, so you need a visitor to tell you which type is which.
The task that I had at hand looked simple: Given a class with methods that has a parameteric return type, get the type argument that is not the class. For example, for this class and method:
public class A { Association<A,B> getAB(); }
Return the element representing the type “B”. Simple enough, no?
Continue Reading »
Guy Wiener on January 11th 2009 in Programming