Replacing nested if statements

南笙酒味 提交于 2019-12-03 03:38:12

问题


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 originator 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 ?


回答1:


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.




回答2:


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.



回答3:


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.




回答4:


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;}



回答5:


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




回答6:


You can just break once a part of the validation failed for example.

function validate(){
  if(b=="" || b==null){
      alert("Please enter your city");
      return false;
  }

  if(a=="" || a==null){
      alert("Please enter your address");
      return false;
  }
  return true;
}



回答7:


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.




回答8:


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.




回答9:


You might also consider using the Visitor pattern.




回答10:


Nested if are equivalent to the logical operator AND

if (condition1)
{
    if (function(2))
    {
        if (condition3)
        {
            // do something
        }
    }
}

Equivalent code:

if (condition1 && function(2) && condition3)
{
    // do something
}

In both cases, when an expression evaluates false, the subsequent expression will not be evaluated. For example, if condition1 is false, the function() will not be called, and condition3 won't be evaluated.




回答11:


Another example some languages allow is this

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

            case j==2
             //action
            break

            case i>j
             //action
            break
           }


来源:https://stackoverflow.com/questions/337037/replacing-nested-if-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!