Closures (Was: Ant and Make)
bofh at stremler.net
Fri Nov 20 12:57:45 PST 2009
begin quoting David Brown as of Fri, Nov 20, 2009 at 05:04:36AM -0800:
> On Fri, Nov 20, 2009 at 12:32:17AM +0000, SJS wrote:
>> Don't want generics, annotations, or god help us, closures.
> Java has had closures for a long time, just no convenient syntax for
> it. Anonymous classes capture variables, which is exactly what
> closures are about.
Anonymous inner classes, yes. And you had to declare the variable final,
too, which helped a little bit.
Making that *easier* is, I think, could well turn out to be a Bad Idea[tm].
> I can understand not wanting generics. I don't know about
> annotations, but closures are invaluable. It moves Java from a
> rediculously verbose language to only an excessively verbose one.
Java's not communist!
> Or do you just like creating an entirely new class, just for the
> purpose of holing a value and having a 'Run' method?
My classes tend to have a bit more behavior than that. The closest I
get to needing closures is in GUI code, when I redirect a bunch of
actions back to methods on the primary class using anonymous inner
And that's just a way to avoid a big switch statement, which is ugly, or
reflection, which is slow and tricky and error-prone. I rarely need to
refer to a variable in the enclosing scope that couldn't just as well have
been passed in on creation.
Methods as first-class objects shouldn't be a problem, so long as the
syntax wasn't excessively ugly. It's the "oh, and I'll refer to the local
variables implicitly" stuff that bothers me about closures... it makes the
code harder to understand for the sake of saving three or four lines of code.
> Then again, the only actual Java I've written in quite some time was a
> single class with a bunch of 'public native ...' declarations, that I
> then call from Clojure. Scala supports native so it isn't even needed
Every public native ... declaration should be decently wrapped in an
interface, and if static, hidden by a containing class. :)
(Yes, I had a bad experience with this. A subcontractor provided a bunch of
code where the math-heavy computation was done in C, and called from a bunch
of public static native methods. Turns out, the performance of these
calculations in Java was within 2% of the native-C computations, but the
JNI overhead swamped all other considerations, making it 20% slower than
the pure-Java solution. But, because they were public *static* calls, we
couldn't fix it.)
Always, always, always profile before you optimize. Then profile after, too.
More information about the KPLUG-List