jamiephelps.com

Proving the sunshine since 1980.

jamiephelps.com header image 2

Programming Style: Two Booleans, Three Possible Cases

September 25th, 2008 · 2 Comments · All Posts

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 [?]

Tags:

2 responses so far ↓

  • 1 Mark Hughes // Sep 25, 2008 at 8:27 am

    If foo and bar are set by logically related tests, there’s likely some common value you can use for them both. Lacking that common value, I’d do this:

    NSInteger choice = (foo ? 1 : 0) | (bar ? 2 : 0); switch (choice) { case 0: // nothing break; case 1: // foo break; case 2: // bar break; case 3: // foo and bar break; default: NSAssert1(NO, @”Invalid choice %d”, choice); }

    This makes it instantly clear that I’ve covered all possible choices; I have to stop and think about the nested if statements every time I come by that code.

  • 2 David A Teare // Sep 26, 2008 at 5:55 pm

    If foo && bar are both false, your first example will execute the else clause, which you comment is “do bar-only stuff”, which is false.

    I think you needed an extra ‘else if’ clause.

Leave a Comment

OpenID

Anonymous

Comments will be sent to the moderation queue.