Dealing with nested if then else/nested switch statements

前端 未结 7 1563
走了就别回头了
走了就别回头了 2020-12-30 08:43

Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?

I remember coming across some methods used by the Google folks

7条回答
  •  轮回少年
    2020-12-30 08:57

    How about:

    /* Code Block 1... */
    
    if(/* result of some condition or function call */)
    {
       /* Code Block 2... */
    
       if(/* result of some condition or function call */)
       {
          /* Code Block 3... */
    
          if(/* result of some condition or function call */)
          {
             /* Code Block 4... */
          }
       }
    }
    

    Becomes this:

    /* Code Block 1... */
    IsOk = /* result of some condition or function call */
    
    if(IsOK)
    {
       /* Code Block 2... */
       IsOk = /* result of some condition or function call */
    }
    
    if(IsOK)
    {
       /* Code Block 3...*/
       IsOk = /* result of some condition or function call */
    }
    
    if(IsOK)
    {
       /* Code Block 4...*/
       IsOk = /* result of some condition or function call */
    }
    
    /* And so on... */
    

    You can of course return if ever IsOk becomes false, if appropriate.

提交回复
热议问题