简化 If 语句的返回

问题描述

我让作者阻止这个 if 语句并简化它。如果嵌套返回相同的值,是否有更有效的方法来实现?我可能只是想念它。

            if (string == "something")
            {
                if (object1 == null || object2 == null || object3 == null)
                {
                    return state1;
                }
            }

            if (attribute1 || attribute2 || attribute3)
            {
                return state1;
            }

            return state 2; 

解决方法

马上,你可以结合你的条件:

        if (string == "something" 
            && (object1 == null || object2 == null || object3 == null))
        {
            return state1;
        }

        if (attribute1 || attribute2 || attribute3)
        {
            return state1;
        }

        return state 2; 

但我会花时间问你为什么有 object1object2object3 等等。

对象的数量可能会发生变化吗?如果是这样,它们会一起改变,还是彼此分开?这些对象和属性是否有相似之处将它们联系在一起?如果是这样,你可能会得到这样的结果:

        var objects = new[]{object1,object2,object3}; // a list of your objects
        if (string == "something" && objects.Any(o => o == null))
        {
            return state1;
        }

        var attributes=new[]{attribute1,attribute2,attribute3};
        if (attributes.Any(a => a))
        {
            return state1;
        }

        return state 2; 

或者这个:

        var things = ...; // each thing has an object and an attribute?
        if (string == "something" && things.Any(t => t.Object == null))
        {
            return state1;
        }

        if (things.Any(a => a.Attribute))
        {
            return state1;
        }

        return state 2; 

另一方面,如果这些对象和属性彼此完全无关,但组合条件有一些特殊之处,您可能需要使用变量名称至少表明您的意图。

        var objectsAreRequired = string == "something";
        var objectIsMissing = object1 == null || object2 == null || object3 == null;
        if (objectsAreRequired && objectIsMissing)
        {
            return state1;
        }
        ...

您也可以结合使用这些技术,这样一来三元运算符可能更具可读性。

var objectsAreRequired = string == "something";
var objectIsMissing = things.Any(t => t.Object == null);
var isBlocked = things.Any(t => t.Attribute);
var errorExists = objectsAreRequired && objectIsMissing || isBlocked;
return errorExists ? state1 : state2;
,

该代码并没有让我感到震惊,但是如果您想摆脱嵌套的 if,您可以这样做:

        if (string == "something" && (object1 == null || object2 == null || object3 == null) || attribute1 || attribute2 || attribute3)
        {
            return state1;
        }

但在我看来,条件过多会使阅读比嵌套的 if 更复杂。另一种选择是这样的:

var meaningfulVariable1 = string == "something"           
var meaningfulVariable2 = (object1 == null || object2 == null || object3 == null)
var meaningfulVariable3 = (attribute1 || attribute2 || attribute3)

return ((meaningfulVariable1 && meaningfulVariable2) || meaningfulVariable3) ? "state1" : "state2"

如果 ternary 运算符变得太复杂,您还可以合并更多变量,也许“meaningfulVariable1”和“meaningfulVariable2”放在一起代表其他东西?

重要的是您的代码可以被其他人轻松阅读。这就是为什么你应该有有意义的变量名。当然,你这里的代码非常通用,所以我可以猜到它的正确名称:-)