Friday, July 2, 2010

how not to branch

As I work on code at work I see a constant theme, one that drives me crazy if goes like this:

for(A){
    if(B) {
        somecode1();
        if(!C)  {
            somecode2();
            if(D || E) {
                somecode3();
            }
        }
    }
}


As you can see it's starting to look like a Christmas tree which isn't very readable. Instead one should write (or refactor) the above code to look more like this:

for(A){
    if(!B) continue;
    somecode1();
    
    if(C) continue;
    somecode2();

    if(!D && !E) continue;
    somecode3();
}

My instructor in college (Dr. Hunter) referred to these as sentinel statements, or something like them. Nesting is not the easiest way to read code and betrays organization. One intends that somecode1-3 gets called in order unless some of the conditions occur. Putting them all in the same indentation gives the reader of your code that impression, by placing code in a nest it's as if your saying "hey this code is one part that could be run, but isn't necessarily what the point of this method is" So I say, indent the optional code, don't for intended code.

No comments:

Post a Comment