例如,当我在我的代码上运行ReSharper时:

    if (some condition)
    {
        Some code...            
    }

ReSharper给了我上面的警告(反转“if”语句以减少嵌套),并建议以下更正:

   if (!some condition) return;
   Some code...

我想知道为什么这样更好。我一直认为在方法中间使用“return”是有问题的,有点像“goto”。


当前回答

这里已经有很多有见地的答案,但是,我仍然想要指向一个稍微不同的情况:而不是前置条件,它实际上应该放在函数的顶部,考虑一步一步的初始化,在那里你必须检查每一步是否成功,然后继续下一步。在这种情况下,您不能检查顶部的所有内容。

当我使用Steinberg的ASIOSDK编写ASIO主机应用程序时,我发现我的代码真的难以阅读,因为我遵循了嵌套范式。它有8层深,我看不出有什么设计缺陷,正如Andrew Bullock上面提到的那样。当然,我可以将一些内部代码打包到另一个函数中,然后在那里嵌套剩余的级别以使其更具可读性,但对我来说这似乎相当随机。

通过用保护子句替换嵌套,我甚至发现了自己的一个误解,即一部分清理代码应该在函数的早期出现,而不是在函数的末尾。对于嵌套分支,我从来没有看到过,你甚至可以说它们导致了我的误解。

所以这可能是另一种情况,反向if可以有助于更清晰的代码。

其他回答

这是意见的问题。

我通常的方法是避免单行if,并在方法中间返回。

你不希望在你的方法中到处都是这样的行,但是在你的方法顶部检查一堆假设是有意义的,只有在它们都通过时才做实际的工作。

我的想法是“在函数中间”的返回不应该那么“主观”。 原因很简单,以下面的代码为例:

    function do_something( data ){

      if (!is_valid_data( data )) 
            return false;


       do_something_that_take_an_hour( data );

       istance = new object_with_very_painful_constructor( data );

          if ( istance is not valid ) {
               error_message( );
                return ;

          }
       connect_to_database ( );
       get_some_other_data( );
       return;
    }

也许第一个“回报”不是那么直观,但这是真正的储蓄。 有太多关于干净代码的“想法”,只是需要更多的实践来摆脱他们“主观的”坏想法。

There are several advantages to this sort of coding but for me the big win is, if you can return quick you can improve the speed of your application. IE I know that because of Precondition X that I can return quickly with an error. This gets rid of the error cases first and reduces the complexity of your code. In a lot of cases because the cpu pipeline can be now be cleaner it can stop pipeline crashes or switches. Secondly if you are in a loop, breaking or returning out quickly can save you a lots of cpu. Some programmers use loop invariants to do this sort of quick exit but in this you can broke your cpu pipeline and even create memory seek problem and mean the the cpu needs to load from outside cache. But basically I think you should do what you intended, that is end the loop or function not create a complex code path just to implement some abstract notion of correct code. If the only tool you have is a hammer then everything looks like a nail.

这当然是主观的,但我认为它极大地改善了两点:

现在很明显,如果条件成立,函数就没有什么可做的了。 它保持嵌套级别较低。嵌套对可读性的伤害比你想象的要大。

保护子句或先决条件(正如您可能看到的那样)检查是否满足某个条件,然后中断程序的流程。它们适用于只对if语句的一个结果感兴趣的地方。所以不要说:

if (something) {
    // a lot of indented code
}

反转条件,如果反转条件满足,则中断

if (!something) return false; // or another value to show your other code the function did not execute

// all the code from before, save a lot of tabs

返回远没有去到那么脏。它允许您传递一个值来显示函数无法运行的其余代码。

你将看到在嵌套条件下应用这个的最佳示例:

if (something) {
    do-something();
    if (something-else) {
        do-another-thing();
    } else {
        do-something-else();
    }
}

vs:

if (!something) return;
do-something();

if (!something-else) return do-something-else();
do-another-thing();

你会发现很少有人认为第一种说法更清晰,当然,这完全是主观的。有些程序员喜欢通过缩进来知道某些东西在什么条件下运行,而我更愿意保持方法流是线性的。

我不是说precons会改变你的生活或让你上床,但你可能会发现你的代码更容易阅读。