What is the benefit of terminating if … else if constructs with an else clause?

前端 未结 12 1030
不思量自难忘°
不思量自难忘° 2020-11-27 13:37

Our organization has a required coding rule (without any explanation) that:

if … else if constructs should be terminated with an el

12条回答
  •  粉色の甜心
    2020-11-27 14:04

    Most the time when you just have a single if statement, it's probably one of reasons such as:

    • Function guard checks
    • Initialization option
    • Optional processing branch

    Example

    void print (char * text)
    {
        if (text == null) return; // guard check
    
        printf(text);
    }
    

    But when you do if .. else if, it's probably one of reasons such as:

    • Dynamic switch-case
    • Processing fork
    • Handling a processing parameter

    And in case your if .. else if covers all possibilities, in that case your last if (...) is not needed, you can just remove it, because at that point the only possible values are the ones covered by that condition.

    Example

    int absolute_value (int n)
    {
        if (n == 0)
        {
            return 0;
        }
        else if (n > 0)
        {
            return n;
        }
        else /* if (n < 0) */ // redundant check
        {
            return (n * (-1));
        }
    }
    

    And in most of these reasons, it's possible something doesn't fit into any of the categories in your if .. else if, thus the need to handle them in a final else clause, handling can be done through business-level procedure, user notification, internal error mechanism, ..etc.

    Example

    #DEFINE SQRT_TWO   1.41421356237309504880
    #DEFINE SQRT_THREE 1.73205080756887729352
    #DEFINE SQRT_FIVE  2.23606797749978969641
    
    double square_root (int n)
    {
             if (n  > 5)   return sqrt((double)n);
        else if (n == 5)   return SQRT_FIVE;
        else if (n == 4)   return 2.0;
        else if (n == 3)   return SQRT_THREE;
        else if (n == 2)   return SQRT_TWO;
        else if (n == 1)   return 1.0;
        else if (n == 0)   return 0.0;
        else               return sqrt(-1); // error handling
    }
    

    This final else clause is quite similar to few other things in languages such as Java and C++, such as:

    • default case in a switch statement
    • catch(...) that comes after all specific catch blocks
    • finally in a try-catch clause

提交回复
热议问题