Wednesday, May 30, 2007

Closures in Java: Why Bother?

Yes, I know Closures are Cool. All the "cool", "new" dynamic languages, like Ruby (which is actually older than Java, BTW), have them, so if Java is going to be "cool", Java needs closures.

Or does it?

My original title for this entry was "Closures in Java: Lipstick on a Pig?", but I decided against that because I don't want to imply any disdain for Java. I've programmed professionally in everything from IBM mainframe assembler language to (shudder) COBOL to Java to Ruby. I spent most of last year developing websites in Ruby on Rails. I currently develop client and server-side solutions in Java.

Professionally, I can't afford to be a language - or even a language-feature - snob. There are things I used to be able to do in assembler language that I can't do in Java, or even (gasp) Ruby. Do you see me writing proposals to add BALR functionality to the Java language? Of course not. Java is not IBM mainframe assembler language. It was never intended to be.

Nor was it intended to be Ruby. Or Python. Or ML. Or LISP. Or whatever your particular favorite non-Java programming language happens to be.

I wish the Java Powers That Be would leave well enough alone, be happy with the success of Java and the JVM, and stop trying to be Everything To Everybody.

Enough with the inferiority complex, already.

So Java doesn't have first-class functions (which some would say aren't essential for closures, but if you're not going to have first-class functions, why bother?). Big deal. It has a large install-base. It has Tomcat. It has the JVM. It has static typing, which is great if you're into that kind of thing. In short, it has everything you need to develop useful, useable, functional programs.

Could Java be a better language? Probably. But could it be worse? Certainly (yes, I'm talking to you, C++).

So why not just let Java be Java? If you really need first-class functions/blocks/closures, use Smalltalk. Or Ruby. Or Python. Or Lisp. If you really need first-class functions/blocks/closures on the JVM, use Smalltalk/JVM. Or JRuby. Or Jython. Or Armed Bear Common Lisp. Or any of the (astonishingly large) number of non-Java languages that have been implemented to run on the JVM.

Here's a thought: look at how JRuby or Jython implement blocks in Java code, and abstract that code into a new library for Java. Or use the existing Jakarta Commons Functor project. There are enough options available that hacking the language spec beyond recognition and bastardizing a decent language in the name of Keeping Up with the Language Jones-es should not have to be considered the only viable option.

Java is a Turing complete language -- by definition, you can do anything in Java that you can in any other Turing complete language. Which means that adding closures to Java, while an interesting theoretical and mental challenge, is not necessary.

So why bother?