Thursday, March 01, 2012

Why no delegates in Java? And will Closures come to Java?

Having worked across Java and .NET platforms, I often compare the features of one over the other. One of the interesting features of the .NET platform is the concept of 'delegates'.

At first, a Java guy may take some time to understand the concept of delegates, but once you are hooked on to it, you tend to use it everywhere...because it is so convienient. The .NET framework uses delegates extensively throughtout its event framework.Java folks have traditionally used the 'Listener' interface pattern for eventing. Even concurrent/parallel libraries in .NET heavily use delegates, whereas Java folks have to still stick with interfaces :(  The closest equivalent to delegates in Java is the anonymous inner class - which IMHO is messy to read and write.

StackOverFlow has a series of interesting discussion threads on this topic:
http://stackoverflow.com/questions/44912/java-delegates
http://stackoverflow.com/questions/2635013/why-not-net-style-delegates-rather-than-closures-in-java
http://stackoverflow.com/questions/1340231/is-there-an-equivilent-of-c-sharp-anonymous-delegates-in-java
http://stackoverflow.com/questions/1973579/why-doesnt-java-have-method-delegates


Another interesting feature that many dynamic languages have is 'closures'. A closure is similar to the concept of delegate, but they are not quite the same. Martin Fowler has a good bliki post explaining the concept of Closures and the difference compared to delegates.

.NET supports both closures and delegates. Found this good article explaning closures in .NET.

No comments:

Post a Comment