I was looking for another approach to implement parsing expressions and came across Visitors in JSR 269 and "The Expression Problem Revisited", "The expression problem (aka the extensibility problem) refers to a fundamental dilemma of programming: Can your application be structured in such a way that both the data model and the set of virtual operations over it can be extended without the need to modify existing code, without the need for code repetition and without runtime type errors."
"All proposals that we know of take as a starting point either a data-centered approach, making it hard to add new operations, or an operation-centered (visitor-based) approach, making it equally hard to add new data types."
"Despite its simplicity, this trick is one of the major contributions of this paper, because it finally moves the visitor-based approach to the expression problem into the realm of static type safety...[it] divides the node classes of the different phases into separate, incompatible families, each characterized, in the form of a type parameter, by the specific brand of Visitor they are capable of accepting."
To put it another way, this enables you to define what implementation of Visitor you wish to use when you construct your visitable classes (at compile time, not runtime) - a pretty neat trick.
Via, why Visitors?.
Update: I've started using these ideas in JRDF to implement the SPARQL query layer and see what practical benefits are.
1 comment:
Hi Andrew,
It would be really good to see some multiple dispatch in Java 6.
Currently all private and (obviously) static method calls use the invokestatic instruction where any protected/public method invocations use the invokevirtual instruction.
Unfortunately the invokevirtual instruction is only bound against the runtime type of the object that the method is called on. There is no way to invoke a method based on the runtime type of it's arguments (well it can be done using a proxy that involves a method table and name mangling but is quite messy).
It would be really nice to see an "invokedynamic" instruction added to the JVM that could evaluate the runtime type of the method arguments. To utilise it, there would need to be a keyword added to the java language to indicate that this type of dynamic binding should be used (as it would be less efficient than standard method binding).
This would remove the need of applying the Visitor pattern in cases where it is used to implement method invocation that is based on the runtime-type of the method argument(s). It would also remove the need for explicit invocation of methods based on runtime argument type using the "instanceof" operator .
Rob
Post a Comment