Site Archive (Complete)
Java Blog: More about Closures
Java
SWAINE'S CAFE

Black. No Sugar. Extra Caffeine.

by Mike Swaine
ERIC BRUNO'S BLOG

Java: The Daily Grind.

by Eric Bruno
October 09, 2006

More about Closures

The debates over Java closures have become heated lately. It really should be about making things simpler.

Some well known people in the Java community, namely Bob Lee, Doug Lea, and Joshua Bloch, have written up an alternative proposal for Java closures (which is a subject I covered in this blog a few weeks ago).

You can view the proposal using Writely (Google’s Ajax-enabled group collaboration application) here.

In this paper, the authors discuss the shortcoming of Java’s current closure implementation: the anonymous inner class. Basically, the problem is that they’re ugly! And with concurrent application development becoming more pronounced with the latest toolkits and frameworks, this can lead to code that’s very difficult to read and maintain.

The authors propose a syntax for closures that removes the keyword new, the actual class declaration, and the method names from the closure definition. Below is an illustration from their paper to prove how this improves code readability:

EXAMPLE 1:

Here is the Java 5 code to start a thread whose run method invokes a method named foo:

new Thread(new Runnable() {
public void run() {
foo();
}
}).start();

With the authors' proposal, the following code would be equivalent:

new Thread(Runnable(){ foo(); }).start();


EXAMPLE 2:

Here is the Java 5 code to sort a list of strings by length (from shortest to longest):

List ls = ... ;
Collections.sort(ls,
new Comparator() {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});

Here is the same code rewritten using the proposed syntax:

List ls = ... ;
Collections.sort(ls,
Comparator(String s1, String s2){
return s1.length() - s2.length();
});

I like the syntax because it’s cleaner, easier to read, and it doesn’t add any new keywords or constructs to the Java language. It simply eliminates some. For more on the closure debate, read Bob Lee’s blog.

What do you think about closures? Is it a lot of hoopla over a relatively obscure new feature, or is it very important to you that the Java folks get this right? Respond to this blog or email me at eric@ericbruno.com

-EJB

Posted by Eric Bruno at 09:19 AM  Permalink




 
INFO-LINK


Related Sites: DotNetJunkies, SD Expo, SqlJunkies