Friday, December 24, 2010

More powerful type casts?

Long time without a single post... Sorry, I've been very busy this year.
There is an interesting discussion about a new, Java-like language in the Apache Harmony developers' mailing list. Yesterday someone proposed a new language feature, a more powerful type cast that provides direct access to the overridden methods of parent classes. Lets see an example:
class Foo {
     void foo() {
    }
}

class Bar extends Foo {
     void foo() {
    }
}
As seen, we have two classes, Foo and Bar. Bar extends Foo and overrides the method foo() declared in its parent.
Bar bar = new Bar();
bar.foo();
If we instantiate Bar, and call foo(), the runtime will execute the method foo() declared in Bar. The proposed feature looks like a normal type cast
((Foo strong) bar).foo();
but forces the runtime to execute the method foo() declared in Foo instead of Bar.foo().
At first sight, this feature seems harmless, but at next, it is a potential disaster. If the runtime allows this, it may cause serious side-effects, if the overriding method contains code that changes the state of the instance. Moreover, the overridden method may not be designed to be called from the given context, so any developer could (even unintentionally) break the design rules of any API by a simple type cast.
On the other side, I do not see any advantages of the proposed feature.