Getting closure on closures
I’m mildly excited about the recent flurry of activity on getting closures into Java.
To recap, closures are little functions which can be treated like objects, and picked up and carried around. Here’s an example from Ruby, which has started the recent buzz on closures — in this case to select all the article published today. The function in curly braces is effectively a parameter passed into the select method:
articles.select {|a| a.isPublishedToday}
(Although closures have been around for some time, and Piers Cawley has quite reasonably quipped that “the buzz about Ruby and Rails is the sound of a bunch of Java programmers finally discovering how cool Perl is”.)
Personally I’ve always thought the functionality was there in Java, thanks to anonymous classes. The counter-argument has been “maybe, but the syntax is unreasonably verbose”, which is true. My counter-counter-argument that being explicit is a benefit, not a drawback, doesn’t feel strong, even to me. This is the verbosity we’re up against in the Java version:
articles.select(new Criteria<Article>(){public boolean meetsCriteria(final Article a){ return a.isPublishedToday(); }});
Hmm… not too nice, really.
Anyway, as Java 5 is the current stable release, and Java 6 is going through beta, so there are now two proposals to introduce closures to Java 7.
First up is Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahé, who might be collectively called BGGA. Their proposal goes fairly deeply into Java, necessitating the introduction of a new type.
Next up is Bob Lee, Doug Lea, and Josh Bloch with “Concise Instance Creation Expressions”, or CICE for short. Their proposal is mostly just syntactic sugar. Introducing CICE Bob Lee says:
Loosely speaking, simple syntax sugar for anonymous inner classes buys Java 90% of the power of BGGA closures while carrying only 10% of the weight.
I like that sentiment. It also reinforces my belief that (verbose) closures were already in Java.
Whichever proposal wins out, it looks like we may yet get some closure on this issue after all.