Sunday, March 15, 2009

'This' type and Covariant builders

When designing your own APIs, either by using interfaces or class hierarchies, you usually find the need to reference the type of the actual implementacion of the interface or class you are writing. This is an actual problem, and there's even a proposal in Project Coin (small language changes for Java 7) to deal with it.

One of this cases, and the one the rest of this post is focused on, is using the 'This' type as the return type of some methods. This is particularly useful for method chaining in fluent interfaces.

Up until Java 5, and the introduction of covariant return types, it was impossible to deal with this issue, which led to frequent casting. But even with Java 5+, the solution is based in manually overriding every method in the subclass (or subinterface) changing the return type to the desired subtype, calling super and returning this.

So, I have checked-in a partial solution to this issue. The type signature of the Type class This<T extends This<T>> (equivalent to that of the Enum class) allows the implementation type to be referenced inside the class, and its value obtained by calling thisValue. But not only the final implementation type, but also some siblings in the hierarchy (as showed in the tests), as the Java type system cannot guarantee this.

That's the reason for the validation in the constructor of This, the reason it is an abstract class instead of an interface, and one of the many reasons it is only a partial soluction.

One application of the This type is for builders (see the builder pattern and item 2 in Effective Java 2nd Ed.). If your builder is part of a hierarchy you are faced with the problem described in this post, so I've also included a base class for them, the covariant builder.
Post a Comment