Consider the following code:


for(item : Type in container) {
if(someEdgeCase) {
// handle appropriately
break;
}

// some code that applies to everything but the above edge case

if(someOtherEdgeCase) {
    // handle appropriately
    break;
}

// some other code that applies to everything but the above two edge cases

if(someMoreEdgeCases) {
    // etc.
    break;
}

// generic code

}

Compare this to:


for(item : Type in container) {
if(someEdgeCase) {
// handle appropriately
} else {
// some code that applies to everything but the above edge case

    if(someOtherEdgeCase) {
        // handle appropriately
        break;
    } else {

        // some other code that applies to everything but the above two edge cases

        if(someMoreEdgeCases) {
            // etc.
            break;
        } else {
            // generic code
        }
    }
}

}

In the former version it is perfectly clear what the “happy path” through the for loop is, in the latter this is hard to see since it’s buried inside the else statements of the edge cases. Having multiple if statements in a for loop might arguably call for factoring out the body of the for loop into it’s own function, but that is not always the best solution (especially if the code in the for loop body depends on variables declared outside the for loop).

I searched yellowgrass on a previous discussion about this but couldn’t find any.

Submitted by Sverre Rabbelier on 2 December 2010 at 00:30

On 2 December 2010 at 14:01 Danny Groenewegen commented:

Note that we do have a case/switch statement to increase readability for nested if-then-else: http://webdsl.org/selectpage/Manual/ActionCode#Switch


On 13 July 2011 at 18:19 Danny Groenewegen commented:

Shouldn’t you have used (and requested) continue instead of break here? Your code will exit the entire loop when it finds one erroneous item. Today I had a similar bug in some Java code and I can now tell from experience that these “features” are evil :)


On 13 July 2011 at 18:19 Danny Groenewegen removed tag feature

On 13 July 2011 at 18:19 Danny Groenewegen tagged wontfix

Log in to post comments