17 January 2013

In his great book Effective Java* Joshua Bloch describes the need to "Know and use the libraries" to write effective code.

The following is an example, where the knowledge of the standard Java libraries leads to much more elegant code.

The code I found was:

for (Map.Entry entry : getMap().entrySet()) {
	if(getMap().containsKey(entry.getKey)) {
		foo(getMap().get(entry.getKey()));
	}
}

So what does the code do? I'll refactor the code on the go so that you can see the steps.

First of all, getMap() returns a field of this class, so we can replace getMap() with map:

for (Map.Entry entry : map.entrySet()) {
	if(map.containsKey(entry.getKey)) {
		foo(map.get(entry.getKey()));
	}
}

The for loop iterates to the entries of map. Entry is a key/value pair tuple.
The if in line 2 asks wether map contains the key of the current entry.

As we just got the entries from the map, it is very unlikely that the map was modified in the mean time.
(And I can asure you that the instance of the class in question is used by one thread only.)

So map.containsKey(entry.getKey) will always return true. What do we do with ifs that always return true? Yes, we'll delete the if immediatly.

for (Map.Entry entry : map.entrySet()) {
	foo(map.get(entry.getKey()));
}

In line 2 (of the refactored code) the map is asked to return the value associated with the key of the current entry.
As every Entry tuple contains both key and value, we can instead ask the entry for the value:

for (Map.Entry entry : map.entrySet()) {
	foo(entry.getValue()));
}

And now we're at a point where the code doesn't tell us what to refactor next. It's where "Know your libraries" come in.
Map has a method values() which returns all the values in the map independently of the key.
Knowing this method, we can simplify the code to:

for (Object value : map.values()) {
	foo(value);
}