tags:

views:

1710

answers:

9

This is related to a chapter from beautiful code. And in that chapter I read about the nested ifs.

The author was talking about deeply nested ifs as orginator of bugs and less readable. And he was talking about replacing nested ifs with case statements and decision tables.

Can anybody illustrate how to remove nested ifs with case (select case) and decision tables ?

+6  A: 

Well, not directly an answer to your question since you specifically ask about switch/case statements, but here is a similar question.

Invert “if” statement to reduce nesting

This talks about replacing nested if's with guard-statements, that return early, instead of progressively checking more and more things before settling on a return value.

Lasse V. Karlsen
+5  A: 

One example I always try to do is replace heavily nested if's like this (actually this one's not too bad but I've seen them up to 8 or 9 levels deep in the wild):

if (i == 1) {
    // action 1
} else {
    if (i == 2) {
        // action 2
    } else {
        if (i == 3) {
            // action 3
        } else {
            // action 4
        }
    }
}

with this:

switch (i) {
    case 1:
        // action 1
        break;
    case 2:
        // action 2
        break;
    case 3:
        // action 3
        break;
    default:
        // action 4
        break;
}

I also try to keep the actions as small as possible (function calls are best for this) to keep the switch statement compressed (so you don't have to go four pages ahead to see the end of it).

Decision tables, I believe, are simply setting flags indicating what actions have to be taken later on. The "later on" section is simple sequencing of actions based on those flags. I could be wrong (it won't be the first or last time :-).

An example would be (the flag-setting phase can be complicated if's since its actions are very simple):

switch (i) {
    case 1:
        outmsg = "no paper";
        genmsg = true;
        mailmsg = true;
        phonemsg = false;
        break;
    case 2:
        outmsg = "no ink";
        genmsg = true;
        mailmsg = true;
        phonemsg = false;
        break;
    default:
        outmsg = "unknown problem";
        genmsg = true;
        mailmsg = true;
        phonemsg = true;
        break;
}

if (genmsg)
    // Send message to screen.
if (mailmsg)
    // Send message to operators email address.
if (phonemsg)
    // Hassle operators mobile phone.
paxdiablo
Because "else if" is evil, and must be written as "else { if ... }"? But you're right to use a switch for simple ifs like this.
JeeBee
+2  A: 

Make the condition into booleans and then write boolean expression for each case.

If the code was:

if (condition1)
{
    do1
}   
else
{
    if (condition2)
    {
        do2
    }
    else (condition3)
    {
        do3;

    }
}

One can write it as:

bool cond1=condition1;
bool cond2=condition2;
bool cond3=condition3;

if (cond1) {do1;}
if (!cond1 and cond2) {do2;}
if (!cond1 and cond3) {do2;}
khivi
A: 

Another example some languages allow is this

           switch true{
            case i==0
              //action
            break

            case j==2
             //action
            break

            case i>j
             //action
            break
           }
Jim C
+4  A: 

How about chained ifs?

Replace

if (condition1)
{
    do1
}   
else
{
    if (condition2)
    {
        do2
    }
    else (condition3)
    {
        do3;

    }
}

with

if (condition1) {
   do1;
} else if (condition2) {
   do2;
} else if (condition3) {
   do3;
}

This is much like switch statement for complex conditions.

Arkadiy
+1  A: 

For decision tables, please see my answer to this question, or better still read chapter 18 in Code Complete 2.

Yuval F
+1  A: 

If and switch statements are not purely OO. They are conditional procedural logic, but do a very good job! If you want to remove these statements for a more OO approach, combine the 'State' and 'Descriptor' patterns.

Anthony Mastrean
you put "not purely OO" as if it was a bad thing!
Javier
That's like *soooooo* 1986. You should be telling people that their code isn't functional enough these days.
Daniel Earwicker
haha, I just happened to read the article recently and figured a directed response may be appropriate
Anthony Mastrean
+1  A: 

You might also consider using the Visitor pattern.

Drejc
+1  A: 

Decision tables are where you store the conditional logic in a data structure rather than within the code itself.

So instead of this (using @Pax's example):

if (i == 1) {
    // action 1
} else {
    if (i == 2) {
        // action 2
    } else {
        if (i == 3) {
            // action 3
        } else {
            // action 4
        }
    }
}

you do something like this:

void action1()
{
    // action 1
}

void action2()
{
    // action 2
}

void action3()
{
    // action 3
}

void action4()
{
    // action 4
}

#define NUM_ACTIONS 4

// Create array of function pointers for each allowed value of i
void (*actions[NUM_ACTIONS])() = { NULL, action1, action2, action3 }

// And now in the body of a function somewhere...
if ((i < NUM_ACTIONS) && actions[i])
    actions[i]();
else
    action4();

If the possibilities for i are not low-numbered integers then you could create a lookup table instead of directly accessing the ith element of the actions array.

This technique becomes much more useful than nested ifs or switch statements when you have a decision over dozens of possible values.

Paul Stephenson