Some bloggers and people I've talked with think of closures in Java as something unnecessary - e.g., "why must we copy C#?". As it happens, most languages have closures, including Java.
A closure is an executable block of code that can refer to free variables from the enclosing scope. Here's an example in Java:
public void example()
{
final double use=Math.random()*10000;
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
System.out.println(use);
}
});
}It's not a great example of how closures are useful. The instance of that anonymous class can reference the variable 'use'. In fact, there's a leak in the implementation that gets into the language - 'use' has to be final. That doesn't stop the anonymous class from being a closure. Let's consider how life would be if Java didn't have closures:public void example()
{
double use=Math.random()*1000;
class MyRunnable implements Runnable
{
private double use;
public MyRunnable(double use)
{
this.use=use;
}
public void run()
{
System.out.println(use);
}
}
SwingUtilities.invokeLater(new MyRunnable(use));
}In fact, that's not far off what the first code sample gets compiled to. In Java 1.0, inner/nested/local/anonymous classes didn't exist, so you'd have to take the above MyRunnable, and put it in a separate file, but the code would be the same otherwise. If you were going to complain about Java getting closures, Java 1.1 was the time to do it!
The above two code samples work in today's Java, and some of you might even favour the second, because it's more explicit - it matches the bytecode more closely.
The way I think is that you should, at least as a thought experiment, take anything like "favour explicit code over abstract code" to an extreme, to test it out. The most explicit you can be in programming is to write assembly code, and none of us wants to do that. Let's flip it around. The most abstract you can be in programming is to write in Lisp, and none of us wants to do that. Both of those statements have holes in them, of course, there are some people who love writing assembly, and there are some who love writing in Lisp. I'm one of the latter.
As it turns out, abstraction is so prevalent in programming that most of us program in languages that are closer to Lisp than they are to assembly. C is the lowest-level programming language that I know, and even it has huge abstractions over the underlying assembly.
Java programmers are already programming on an abstraction, the Java Virtual Machine, before they even worry about syntax. It seems that we already favour abstract code over explicit code. Abstract doesn't mean imprecise, or vague, it's another way of saying "general". We can use abstractions to stop repetition.
Consider the above code samples as templates of some kind:
final $TYPE $VAR=$VAL;
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
$ACTION($VAR);
}
});and $TYPE $VAR=$VAL;
class $BLAH implements Runnable
{
private $TYPE $VAR;
public MyRunnable($TYPE $VAR)
{
this.$VAR=$VAR;
}
public void run()
{
$ACTION($VAR);
}
}
SwingUtilities.invokeLater(new $BLAH($VAR));The first template has 4 parameters, $TYPE, $VAR, $VAL, $ACTION. It mentions $VAR twice, the others once each.
The second has 5 parameters, $TYPE, $VAR, $VAL, $ACTION, $BLAH. It mentions $TYPE 3 times, $VAR 6 times, $VAL once and $ACTION once. We're always taught not to repeat ourselves in programming, and we can easily see that the second template is more repetitive than the first. A less well-known rule is to avoid unnecessary names. MyRunnable is a name that's defined once and used once - a bad sign.
Extra repetition means extra scope for errors. You might change 'use' between calling invokeLater and invokeLater actually happening - now you've got a sync problem. This is because you had to copy your variables yourself. Admittedly, thanks to the 'final' restriction, Java doesn't help much there, but at least it stops broken code from compiling.
Let's briefly return to the restriction that the local variables that anonymous classes capture must be final. Does that stop anonymous classes from being closures? Changing the values of variables is kind of an optional feature in programming languages. Mathematics seems to have managed without x++ for many years. Java's anonymous classes place some restrictions on what kind of variables are considered free, but that doesn't stop them from being closures. Haskell definitely has closures, and definitely doesn't have mutable variables.
Ok, with all that out of the way, we now know that Java has closures, and they aren't disappearing anytime soon. Let's take a moment to laugh at the blog posts (actually most of them are anonymous comments on blogs) saying that Java doesn't need closures.
There. Now let's briefly examine why Java needs better closures, by returning to our template. This time we're going to read it with boilerplate glasses:
boilerplate double use=Math.random()*10000;
SwingUtilities.invokeLater(boilerplate System.out.println(use)); What we'd like to do now is to make that boilerplate disappear. Scala has an interesting way of doing that: val use=Math.random*10000
invokeLater(System.out.println(use))Scala methods can have lazy parameters, that is, parameters that are not evaluated at call time, but are evaluated when the method wants to. You can use that to write your own if method, e.g.: myIf(Math.random<5,System.out.println("Still here"),System.exit(0))Of course, myIf is just an interesting result, and not actually useful, but in the case of invokeLater it is useful; it gets rid of a lot of our boilerplate.
Java 7 closures let us do pretty much the same thing:
double use=Math.random()*10000;
SwingUtilities.invokeLater({=> System.out.println(use));There is another syntax for the last line: SwingUtilities.invokeLater()
{
System.out.println(use);
}We still have a little boilerplate with both these syntaxes, but not enough to need the boilerplate glasses. Sadly, despite it being technically possible for IDEs to become boilerplate glasses, they haven't done so. Folding an anonymous class in IDEA looks like: new Runnable(){...}They've folded the wrong thing. Duh. It should look more like: new ...{System.out.println(use);}Some people think that Java doesn't need better closures because Java as a language is already broken in many ways. Often Scala is quoted as the next Java. I've tried Scala out - it's very impressive, and similar enough to Java to not have too many surprises. So in one sense I agree, but I also think that Java should have better closures to move the status quo of programmers up a notch. Programmers should consciously favour abstraction over boilerplate, instead of the current situation, where many use abstractions all the time but are reluctant to invent their own.
Being free of boilerplate lets you think in different ways. My post on point-free programming shows one route you could take - there are many others.