Nelz' Blog

Ruminations on Development


« Previous day (Apr 15, 2008) | Main | Next day (Apr 17, 2008) »
Wednesday Apr 16, 2008

Java 5 FOREACH Syntax

For those that don't currently use the new Java 5 "foreach" syntax, you are missing out.

I got to a point today where I wanted to verify that the construct is doing the intelligent thing, so I wrote the following unit test:

	@Test
	public void forEachLoop() {
		for (String str : doHeavyWeigthMethod()) {
			System.out.println(str);
		}
 	}

	private List<String> doHeavyWeigthMethod() {
		System.out.println("heavyMethod");
		final List<String> results = new ArrayList<String>();
		results.add("one");
		results.add("two");
		results.add("three");
		return results;
	}

I was psyched to see the output:

heavyMethod
one
two
three

Basically, this shows that the foreach construct only evaluates the collection once and caches the value to be used in each iteration.

However, the construct is not without some pitfalls. I would have expected the new construct to be programmed more defensively, but it is still susceptible to NullPointerException. Running the following throws the NPE:

	@Test
	public void forEachLoop() {
		for (String str : doHeavyWeigthMethod()) {
			System.out.println(str);
		}
 	}

	private List<String> doHeavyWeigthMethod() {
		return null;
	}

So, unless you know you are in control of the method you are calling in the expression part of the "foreach" construct, you still need to defensively check for null. And, we all know how much I love that, right?

History Meme

I found a new meme spreading amongst the technorati... The "history" meme. (See previous examples here, here, and here.)

Basically, you run a script to show what commands you frequently use.

Here's my output:

$ history|awk '{a[$2]++} END{for(i in a){printf "%5d\t%s \n",a[i],i}}'|sort -rn|head
  102   svn 
  100   ls 
   74   cd 
   49   wget 
   31   ruby 
   28   rm 
   13   exit 
   10   gem 
    9   which 
    8   mv 

What is yours?