{ by david linsin }

September 02, 2008

Series Reflections: Put Closures into Java 7

About this series: From time to time I'll take a look at blog posts from my archives and reflect on my views and opinions from back then.

After Neil Gafter released a feature complete prototype of the BGGA Closures Proposal I decided I'd give it a try and play around with it a little.

It's funny, because my opinion on Closures has changed quite a bit, since my first encounter. I was very skeptical in the beginning. Wouldn't the concise syntax of closures hurt the language in terms of readability and comprehensibility? I came to learn that you can get used to concise and thus more complex syntax. That doesn't mean it promotes readability, to the contrary. I still believe it hurts Java's readability a lot, but in order for Java to move on, Closures are necessary. That's the reason why I think Closures should be included in future versions of the Java language.

I bet you know this feeling: after playing around with a technology for a while, you start to get the hang of it and all of the sudden you have a bunch of really cool ideas, on how you could use this stuff in your production code. It happens to me a lot and after I gave Neil's prototype a test run, I had the same feeling about Closures. For example there's the possibility to catch multiple Exceptions with one catch clause:

Statement stmt = null;
try {
// do stuff that uses Statement instance
} catch (SQLException | NullPointerException | Exception e) {
// handle state
log.error(e);
} finally {
try {
stmt.close();
} catch (Exception ex) {}
}

This feature alone is worth adding Closures to the Java language. However, it's only the beginning. The whole control abstraction capability which Closures and thus BGGA offer, give you the possibility to write more clean and concise code. You can wrap all your boilerplate code that you need to write in order to close connections, files or dispose other resources.

public void connect({ ==> void } block) {
try {
block.invoke();
} catch (Exception e) {
// handle e
}
}

// don't bother about connections
connect() {
Connection con = ....
}

This simple example illustrates how powerful control abstractions are. I can think of so many spots in my code where I could have used this and it's only a small part of Closures.

Of course there is a downside: complexity. You can find a lot of BGGA Closures examples, highlighting how powerful the concept is and at the same time ruthlessly demonstrating how complex your code could get. You basically add another layer of abstraction and it not necessarily hides complexity.

I think if you build an easy API, that doesn't go over board and simplifies an every day annoying coding problem, you can win over a broad range of Java developers to the closures camp. After all, it worked for me!

0 comments:


com_channels

  • mail(dlinsin@gmail.com)
  • jabber(dlinsin@gmail.com)
  • skype(dlinsin)

recent_postings

loading...