Friday, February 01, 2008

Today's Java Irritant: No sense of closure.

There's still enough back-and-forth about the inclusion of closures in Java 7 that I'm nervous it might not make it in to the language.

James Gosling supports the addition of closures and states that the reason they weren't there in the first place was due to time pressures and seems to have some regret about their absence (understandable; he's a Pretty Smart Dude and probably feels the pain of Java wartage more keenly than most).

Ricky Clarkson blogs about why we need a new syntactic construct to make the use of closures cleaner and less verbose, even while admitting that Java does, in fact, have a form of support for closures already.

My languages of choice (Lisp, Smalltalk, Ruby, etc.) all have cleaner support for closures without the syntactic overhead that current Java has. For a trivial example we can compare the use of closures for processing a file.

file.each_line do |line|
# Process line of file.
end

With current Java syntax we might end up with something like this:

import static bar.baz.eachLine;
...
eachLine(file, new EachLine() {
void doLine(String line) {
// Process line of file.
}
});

We could also create a File-like object with an eachLine method.

This isn't the Worst Syntax in the World, but it still makes me think more when writing the code and when I'm reading it later.

A relatively minor point is that any variable used in the closure must be declared as final in the enclosing method. This may obfuscate the actual functionality of the enclosing method and, in some cases, require the introduction of a final variable just to satisfy the requirements of Java's current "closure" syntax/implementation.

It'll be interesting to see what finally happens; I hope that (a) support for closures is added and (b) it doesn't irritate me too much.