Replacing nested if statements

前端 未结 11 1905
春和景丽
春和景丽 2020-12-23 20:44

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 if

相关标签:
11条回答
  • 2020-12-23 21:37

    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;}
    
    0 讨论(0)
  • 2020-12-23 21:39

    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;
    }
    
    0 讨论(0)
  • 2020-12-23 21:40

    Another example some languages allow is this

               switch true{
                case i==0
                  //action
                break
    
                case j==2
                 //action
                break
    
                case i>j
                 //action
                break
               }
    
    0 讨论(0)
  • 2020-12-23 21:43

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

    0 讨论(0)
  • 2020-12-23 21:43

    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.

    0 讨论(0)
提交回复
热议问题