How do you handle huge if-conditions?

后端 未结 21 1726
一向
一向 2021-01-31 17:14

It\'s something that\'s bugged me in every language I\'ve used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, u

相关标签:
21条回答
  • 2021-01-31 17:55

    Steve Mcconell's advice, from Code Complete: Use a multi-dimensional table. Each variable serves as an index to the table, and the if statement turns into a table lookup. For example if (size == 3 && weight > 70) translates into the table entry decision[size][weight_group]

    0 讨论(0)
  • 2021-01-31 17:56

    Separate the condition in several booleans and then use a master boolean as the condition.

    bool isOpaque = object.Alpha == 1.0f;
    bool isDrawable = object.CanDraw && object.Layer == currentLayer;
    bool isHidden = hideList.Find(object);
    
    bool isVisible = isOpaque && isDrawable && ! isHidden;
    
    if(isVisible)
    {
        // ...
    }
    

    Better yet:

    public bool IsVisible {
        get
        {
            bool isOpaque = object.Alpha == 1.0f;
            bool isDrawable = object.CanDraw && object.Layer == currentLayer;
            bool isHidden = hideList.Find(object);
    
            return isOpaque && isDrawable && ! isHidden;
        }
    }
    
    void Draw()
    {
         if(IsVisible)
         {
             // ...
         }
    }
    

    Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU!

    0 讨论(0)
  • 2021-01-31 17:56

    As others have mentioned, I would analyze your conditionals to see if there's a way you can outsource it to other methods to increase readability.

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