Wednesday, November 18, 2009

Java and Closures - own goal

Today in the morning there was an announcement made that closures (a feature long awaited in Java) will make it to version 7. Here you'll find some examples of how it will actually look like.

But...

To have an understanding of what closures really are useful for one must follow an example. Here's something written in C# for sorting a list of strings:

var list = new List<string>() {...content go here...};
list.Sort({ (s1, s2) => s1.Length - s2.Length });

And here's the equivalent in Java:

List list = ...
Collections.sort(list, #(String str1, String str2) {
return str1.length() - str2.length();
});

One can clearly see the intent of what the closure (a function being passed as parameters) looks like in both languages with the clear winner in succinctness being C# (or pretty much any other modern language out there). I know that java tends to be verbose on all possible counts but having a different approach for commonly understandable constructs is a bad thing all along.

One other thing that you can clearly see in the example above is the lack of type inference feature which makes the syntax even more verbose.

So when I said "own goal" in the title what I really meant is that the primary function, which is succinctness and clarity has been lost in transition.

Unfortunately we're facing yet another messed up implementation of a perfectly good idea (like generics with type erasure) in one of the most popular languages in the industry.
With this kind of mind set the end is near!

C ya!

No comments: