It was a late evening when I fall in buggy a code like this:

Destination newDestination = null;
if (! originalDestination.getId().equals(getDestinationId()));
{
    newDestination = context.loadDestination(getDestinationId());
    prefix.setDestination(newDestination);
}
context.save(prefix);
if (newDestination != null)
{
    newDestination.addPrefix(prefix);
    originalDestination.removePrefix(prefix);
    context.save(originalDestination);
    context.save(newDestination);
}

When the first if block is true, the second one will also be true, because the line at 4 will force newDestinatio to be not-null. The strange thing was that the second if-block was always executed, so I started to do step-by-step debugging. Working with cglib-proxied objects (hibernate) I was starting to think on some bug somewhere in the framework. Wrong! The bug is there and was under my nose but nicely hidden. Can you see it?
Check the end of line 2, at the end of the if condition... there's a ";" so that the first if will execute an empty statement, and the block under the if will ever been executed. It was so surprising checking internal values thru the debugger and then see the if being executed even if the condition was false!

I was surprised tha Eclipse does not pointed me over the code inconsistency (a warning). If you enable warning on empty statements (Preferences->Java->Compiler->Errors/Warning->Potential Programming Problems->Empty Statements), you could notice easier errors like this. But there's no way to define a warning of blocks {} without a previous construct (if/while/for...). Even if sometime correctly used, empty blocks are always ugly (i.e. for(int i=0; i>x; doSomething(i++)); ugly!). So I enabled this as an error, in eclipse compiler. Would be nice to be warned on instruction blocks without a construct on top (like the range of lines between 3 and 6).


No Responses to “Infamous programming errors on curly braced {blocks}”  

  1. No Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



Calendar

June 2005
M T W T F S S
    Jul »
 12345
6789101112
13141516171819
20212223242526
27282930  

Follow me

twitter flickr LinkedIn feed

Subscribe by email

Enter your email address:

Archives


Categories

Tag Cloud


Listening