GLAT: Google Labs Aptitude Test Effective Enterprise Java: Writing a foreward for Ted
Sep 09

Martin Fowler on Closures

Tech Add comments

Closures are so great. And anonymous inner classes are NOT “Good Enough”.

However, some people don’t grok closures and think that they are “just function pointers / method objects / …”

Martin Fowler has written a nice simple piece which gets across the major points:

So the first crucial point about closures is that they are a block of code plus the bindings to the environment they came from. This is the formal thing that sets closures apart from function pointers, anonymous inner classes and similar techniques.

The second difference is less of a defined formal difference, but is just as important, if not more so in practice. Languages that support closures allow you to define them with very little syntax. While this might not seem an important point, I believe it’s crucial – it’s the key to make it natural to use them frequently. Look at Lisp, Smalltalk, or Ruby code and you’ll see closures all over the place – much more frequently used than the similar structures in other languages. The ability to bind to local variables is part of that, but I think the biggest reason is that the notation to use them is simple and clear.

I would be a very happy man if closures came into Java as a first class citizen, like other languages :)

One Response to “Martin Fowler on Closures”

  1. James Strachan Says:

    Closures have made it into C# 2.0, though they call them delegates and they’re more verbose than most of the alternative implementations (though they are typesafe).

    Note that at the bytecode level, there’s no such thing as checked exceptions, so it is possible to add to a java-like language pretty easily (Groovy, JRuby, Nice etc)

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: What are the first four letters in the word British?