Home > MDSD, The How, Xtext > Polymorphic dispatch in Java using Xtext

Polymorphic dispatch in Java using Xtext

One of the very nice features of both Xtend and Xpand is polymorphic dispatch (also called multiple dispatch, at times). For the truly uninitiated: if you are dealing with an overloaded function/method, polymorphic dispatch is the mechanism that chooses which one to actually call based on the runtime types of the arguments. Note that most compiled and/or statically-typed languages (such as Java) determine which implementation to call at compile-time. The consequence of this is that if you want behavior to depend on runtime types, you’re forced to use a lot of

        if( obj instanceof SomeSubtype ) {
            doSomethingWith((SomeSubtype) obj);
        }
    ...
    private void doSomethingWith(Somesubtype subObj) {
        ...
    }

in your code.

On the other hand, several dynamic languages (like Groovy and Scala) feature polymorphic dispatch. We also see this feature used in several places in Xtext runtimes, m.n. in sub classes of AbstractDeclarativeScopeProvider and DefaultDeclarativeQualifiedNameProvider. This magic is provided courtesy of the org.eclipse.xtext.util.PolymorphicDispatcher class. Since that class itself has no runtime dependencies on the rest of the Xtext runtime framework, we can use it ourselves outside the context in which it is normally used. This blog will explain how to do that.

I’m going to re-use the path expressions in entity models example and re-implement the scoping required. Please check that blog to see that the implementation of the scope_PathTail_feature method was rife with instanceof‘s and explicit casts. To remedy that we’re going to the PolymorphicDispatcher. The class has a number of constructors and static factory methods, but the easiest to use is the one with signature createForSingleTarget(String methodName, Object object) which returns a PolymorphicDispatcher object that does dispatches polymorphically to methods with the given methodName inside the given object. (Alternatively, you could use createForSingleTarget(String methodName, int min, int max, Object object) to limit the number of parameters -e.g., in our case: min=max=1.)

Now we only need an object which holds the methods to dispatch to. For that, I usually create a separate (top-level) class whose sole responsibility it is to compute “something” using polymorphic dispatch, e.g. a scope. This class holds all the methods to dispatch to as private methods and exposes one public method to actually trigger the computation. This has a number of advantages:

  • It provides a clear separation between “polymorphic code” and plain Java code. The dispatch methods can’t be called by accident and
    forced to think about the computational context. It find it also encourages a more functional way of thinking.
  • The private methods aren’t actually used anywhere so they generate “…never used locally” warnings. By endowing the separate class with a @SuppressWarnings( "unused" ) annotations (only) those warnings disappear.

In the case of the path expressions, our code eventually looks like this:


As you can see, the number of instanceof‘s and explicit casts has reduced to 0. For simplicity I’ve use an inner class called PolymorphicContext here so it can access the structuralFeatures(Entity) method (which is reused verbatim from the earlier post), but in general, I’d recommend using a top-level class. The scope_PathTail_feature method is now reduced to a simple call to the computeScope method of the PolymorphicContext class. The computeScope method, in turn, simply uses the single PolymorphicDispatcher object to polymorphically dispatch to methods called “scope” on this object and produces a suitable IScope object from the result. The first two scope methods correspond to the two outermost if( context instanceof …) statements in the original code. The other scope methods correspond to further such instances of if-statements.

Note that I re-use the dispatcher object for that as well: again, this is mostly for the sake of simplicity. In practice I’d recommend either using a separate class or a separate dispatcher object. What you’d choose, depends on the granularity. In this case, it all fits in relatively comfortably in one class but if you accumulate dispatching methods, you’re probably better off separating concerns as well as possible.

This example also demonstrates some disadvantages of this approach:

  • There’s some boilerplate code involved, so this approach only makes sense if there’s a fair number of dispatch targets. Already in the example, there are more lines of code in this implementation than in the regular Java one which doesn’t help overview and clarity.
  • This type of code is generally a bit harder to read and understand in an imperative manner than a regular, well-laid out implementation. Again, you should consider whether your code will really benefit from this approach.

Conclusion

This blog demonstrates the (relatively simple) use of polymorphic dispatch in Java through Xtext’s PolymorphicDispatcher class, combined with something of a Best Practice. There’s a lot more the PolymorphicDispatcher class than I’ve shown here, which unfortunately is quite undocumented. In my opinion, the best way to find out more is by digging into the code, both of the class itself as clients of it, and then imitating those usage patterns in your own code.

P.S.: Be sure to also check out Sven Efftinge’s blog entry on polymorphic/multiple dispatch.

Advertisements
Categories: MDSD, The How, Xtext
  1. Ronk
    December 15, 2010 at 8:55 pm

    What a horrible term, this polymorphic dispatch. Multi methods, multi dispatch or (best of em) external polymorphism so much better convey what’s actually going on. And that should count for something 🙂

    • December 15, 2010 at 9:01 pm

      Sure, but it’s the term that happens to be used in/for the Xtext framework and I chose to stay close to that 😉 You’re free to use “MultiMethodsContainer” and “multiDispatcher” in your own code!

  2. December 16, 2010 at 9:38 am

    Nice post!
    It set me up and running with PolymorphicDispatcher in just a few minutes, and it really rocks!

    @Ronk: well the term might not be that good, but PolymorphicDispatcher is NOT multi-methods, since it’s not a linguistic extension of the language Java, which does NOT provide multi-methods or dynamic overloading. It’s a nice work around to achieve the same result, but it’s not multi-methods (for instance, there’s no static checking, and you might get NoSuchMethods exceptions).

    Just my two cents.

    Still Xtext PolymorphicDispatcher is really useful for programming.

    Thanks Xtext guys 🙂

  1. March 21, 2011 at 11:16 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: