This is a great example of getting stuck in a mindset. A piece of very poorly written Java code is presented followed by a much shorter piece of Groovy code and Groovy is declared the winner.
The original Groovy:
list = ["Rod", "James", "Chris"]
shorts = list.findAll { it.size() <= 4 }
shorts.each { println it }Java:
for ( String item : new String[] {"Rod", "James", "Chris" } ) if ( item.length() <= 4 ) System.out.println(item);oooo, one line! It must be good...
Of course if I were actually going to write that, I'd write it as:String[] items = { "Rod", "James", "Chris" };
for (int i = 0; i < items.length; i++) {
if (items[i].length() <= 4) {
System.out.println(items[i]);
}
}It's much clearer that way and it's compatible right back to Java 1.1 as far as I'm aware.
The problem the original author had was that he had written something in Groovy and thought that the best way to do it in Java was directly comparable - it's not. In Groovy, lists and arrays are extremely similar, in Java they're very different. Thus, in Groovy the choice between a list and an array in this case made no difference, but in Java it made a huge difference.
Similarly, Groovy made it much easier to use a filter to create a second list whereas in Java it was significantly simpler and clearer to just selectively print from the original list. By getting stuck in the Groovy mindset instead of adapting to the current programming language, the programmer wrote poor quality code that was hard to maintain. Worse still, they then blamed their tools. For shame!
Astute readers might note my own blaming of tools in my last post but they'd only be partially correct. I criticized C for making buffer overflows possible - I'd also criticize the programmer for actually writing the buggy code.
DrBacchus says:
Strangely, I find myself looking at your examples, and declaring Java the clear winner here, for the simple reason that magic variables are the source of lots of clarity problems, particularly for the beginner. Where did this magic variable “it” come from? What is it’s scope? Can I use it again after this block is over? That is, at the end of the loop, does “it” retain the last value, or does it simply go away?
I know this is very strange to hear coming from a Perl programmer, but variables that simply spring into existence (like magical loop variables) are just too prone to confusion. Yes, of course, Perl has a plethora of these, but they are most valuable for one-liners and obfuscation, and are best avoided for things that one might actually want to maintain.
It also bugs me the way that people comparing languages write stuff in the “evil” language in such a way that is as unreadable as possible. Would any real programmer actually write that all on one line like that? Does that programmer deserve to be shot?
Dunno. I find it’s possible to write crappy unreadable code in any language.