Late Thursday afternoon, in a packed room 8 of the JavaPolis venue, Neal Gafter presented his plans for adding closures to Java. He had a very well built up argumentation for why we need closures in Java. Not the usual story about the visitor pattern and putting responsibility in the object where it belongs (e.g. iterating should be done by the collection, not by the code that uses the collection). Neal’s argument was all about control abstraction. As it is right now, if you want to enclose some code–for instance, to enclose it with start/end transaction code, or with code to open and close a file that you’re using in the enclosed code–you can do that by creating an anonymous inner class containing the code, and sending that off to the enclosing code. Something like this:
openFile(file, new Executor() {
public void run(Object o) throws Exception {
Reader r = (Reader) o;
r.read(...);
}
});
where openFile
will look something like this:
public static void openFile(File f, Executor e) throws Exception {
Reader r = new FileReader(f);
try {
e.run(r);
} finally {
r.close();
}
}
No problem here–until you try to ‘communicate’ with the anonymous inner class. Say you want to set some boolean depending on the contents of the file you’re reading. You can’t–that boolean has to be declared final for it to be visible inside the inner class. And this is just one of the problems you may encounter, like when you want to throw an exception from the inner class. You can work around all of those problems by refactoring the enclosed code. But that’s exactly the point Neal was making: you shouldn’t have to change your code.
In short, the proposal he wrote (together with Gilad Bracha, James Gosling and Peter von der Ahé) would make it possible to write:
openFile(Reader r: file) {
r.read(...);
}
This looks nice enough; until you see the code that makes this possible. Unfortunately, in order to optimally fit everything into the existing language structures, a monstrous method declaration involving lots of ugly generics is needed.
Then in the evening, Neal did a small scale BOF session on the same subject, going into more detail. We discussed things like, what arguments exist against adding closures, and also the alternative proposal for which Neal had little praise. If only all JavaPolis sessions could be like this: an audience of 15 instead of 500, a small room, every opportunity to ask questions directly and discuss them in detail.
The proposal can be found at http://javac.info.