Delegates in Java - Why not?
In his post, Amr from EJUGS points out that he tries to implement the powerful delegates of C# in Java, in his words. Even though I am a C# developer as well, and see the power they serve, I don't agree with some of his claims.
First, both papers are still relevant even though old. I agree with both almost completely. The thing is, Microsoft doesn't address the fact that delegates take a lot of the object-oriented out of the language. Sun, on the other hand, aren't pure either.
In C#, when you write the keyword "delegate", a class is created to wrap any arbitary number of methods with the same signature. The compiler is the one making sure the signature is the same, as this wrapper class only receives an object (to invoke on) and a method identifier (to invoke). Then, when the delegate is invoked, it actually uses reflective methods to invoke the method(s). No wonder Amr claims that [most] implementations uses reflection to invoke the method.
Is that considered powerful? Java on the hand, since it uses classes implementing a single interface, is using direct invocation, and doesn't use reflection (which known to be extremely slow) in any part of it. Since annonymous classes can be used, the amount of written code isn't that bigger: Even by Microsoft's blown measurements, it was increased by less than 10%, which is in most likelihood the new ActionListener() { lines.
In Amr's implementation of the
Delegate class, he hard-wired the method Job to be with the signature of Job(Stirng). That means a new Delegate class implemented, with all his code, for every signature. That said, he claims to have a better version that doesn't. If he does, I wish to see how it's implemented - Out of my own curiousity, and to see that it doesn't prevent type-safety, as I suspect it does.
I don't mean to bash out at Amr's work. It's good that people try to innovatively add abilities to the Java language. However, what makes delegates work in C# is not the language but rather the dotNet compilers. Without creating a good pre-compiler for Java, delegates would not be introduced in the same "powerful way".
If you ask me, I don't think they should be in Java. There's a reason why they stayed out, even though as the papers show Sun and Microsoft had the fight about it way back in 1998. The reason is object-oriented design, and the "magic factory". In any case, Java events are implemented using the observer-observable design pattern. I think what we should do is focus on easier implementations of this design pattern. I know I'm not very objective, but the ListenersCollection class is a good example.
This is the second time I say something in response to EJUGS... I hope they don't hate me over there by now..
Comments (7)