编码大型嵌套功能块时的经验法则

use*_*015 4 c# refactoring

我已经在c#编写了一段时间,并且通常对编码标准的经验法则有很好的了解.我最近鼓励我的大学采用基于结果的方法来编写功能块,而不是嵌套逻辑块,并且正在寻求你的建议.下面是我正在谈论的一个例子,其中一种情况的结果用于确定代码路径而不是嵌套.有人建议这种方法更容易阅读,特别是如果结果需要多层嵌套,但我更喜欢使用Curly定律和重构方法和函数,其中嵌套变深.

private void MethodOne()
    {

        bool CarryOn = false;

        // first layer
        if (ValidationRuleOne() == true)
        {
            CarryOn = true;

        } else {

            CarryOn = false;
        }

        // second layer
        if (CarryOn) 
        {
            CarryOn = ValidationRuleTwo();

        } else {

            CarryOn = false;
        }

        // third layer
        if (CarryOn)
        {
            CarryOn = ValidationRuleThree();

        } else
        {

            CarryOn = false;
        }

    }
Run Code Online (Sandbox Code Playgroud)

这种方法对我来说似乎不对,因为我建议将该方法重写为..

        private void MethodOne()
    {



        // first layer
        if (ValidationRuleOne() == true)
        {

            // second layer
            if (ValidationRuleTwo() == true)
            {

                // third layer
                if (ValidationRuleThree() == true)
                {


                }

            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

如果嵌套变得太复杂,那么我建议需要重新考虑方法/函数结构以将逻辑功能组分组到另外的方法或函数中吗?

任何想法都非常感激.

问候,

蒂姆

kem*_*002 10

if (ValidationRuleOne() == true)
    {

        // second layer
        if (ValidationRuleTwo() == true)
        {

            // third layer
            if (ValidationRuleThree() == true)
Run Code Online (Sandbox Code Playgroud)

可:

if(ValidationRuleOne() && ValidationRuleTwo() && ValidationRuleThree())
{
...
}
Run Code Online (Sandbox Code Playgroud)

在我看来更容易阅读.

如果由于某种原因,您需要触发每个验证规则:

if(ValidationRuleOne() & ValidationRuleTwo() & ValidationRuleThree())
{...} //note the & vs &&
Run Code Online (Sandbox Code Playgroud)

(并且您不需要执行if(validationRule()== true),因为验证返回一个布尔值,您不需要将它与条件语句中的一个进行比较).


Jer*_*rts 7

我个人喜欢使用保护条款.

if (!ValidationRuleOne()) 
    return;

if (!ValidationRuleTwo())
    return;

if (!ValidationRuleThree()) 
    return;
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 6

你不是只是从else块中返回而不是将"CarryOn"设置为false的任何原因?

我同意Kevin的使用建议,&&如果你没有别的事情要做......我假设在现实生活中你在if和else块中有其他代码.如果你不这样做,你绝对应该使用&&.

另外,在风格方面: