Programming Style: Two Booleans, Three Possible Cases

Posted: September 25th, 2008 | Author: Jamie Phelps | Filed under: All Posts | 2 Comments »

Quick programming style question. If you have two boolean values and want to have a different outcome for each alternative and the case where both are true, how do you do it?

Here are the two options I have come up with.

First, a straight if-else if-else block like this: Update: I have updated this first option to reflect Dave’s comment below.

if(foo && bar){
    //do foo&bar stuff
} else if(foo){
    // do foo-only stuff
} else if(bar){
    // do bar-only stuff
}
//perform final computations

Second, nesting if clauses like this:

if(foo || bar){
    //set up assuming foo && bar
    if(!foo){
        //remove foo-specific stuff
    }
    if(!bar){
        //remove bar-specific stuff
    }
    //perform final computations
}

Or perhaps there’s a better way that I haven’t considered. I’d be interested to see how you handle this. Let me know in the comments or a post on your own blog.

Popularity: unranked [?]