11 January 2013

At a client I recently reviewed eclipse compiler settings and resulting warnings.
I stumbled upon a warning which I've never seen before: Empty control-flow statement.
As I'm always interested in new findings, I immediatly headed over to the source code:

Object object;
for (Long id : ids) {
	object = foo(id);
	if (object != null && bar(object))
		;
	break;
}

eclipse annotates the semicolon in line 5 with the warning "Empty control-flow statement".
Looking at the code, it seems that there's either a bug or the code is way too complicated.

Option 1 - Fix the Bug

I guess the original intention of this code was to search for a valid object for an id in the ids list.
Actually the code tries to get the object for the first id in ids, independent of whether it's null or the object satifies bar(object).
The fixed code would look like:

Object object;
for (Long id : ids) {
	object = foo(id);
	if (object != null && bar(object)) {
		break;
	}
}

Option 2 - Simplify the code

If it's not a bug, the code can be written like this:

Object object = bar(ids.get(0));

No need for a for loop, no need for a null check, no need for bar(object).

But I still believe, option 1 is the right one.

Conclusion:

Always take care of the warnings your compiler issues. Every single warning shows either a bug, opportunities for improvement (or is obsolete).
I'll write about obsolete warnings in a future post.