Stuck In A Mindset
By Adrian Sutton
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.