是否有充分的理由说明在函数中只有一个return语句是一个更好的实践?

或者在逻辑上正确的情况下,可以从函数中返回,这意味着函数中可能有许多返回语句?


当前回答

没有人提到或引用代码完成,所以我就这么做。

17.1返回

尽量减少每个例程的返回次数。如果在底部阅读一个例程,你没有意识到它可能会返回到上面的某个地方,那么理解它就更难了。

在增强可读性时使用返回。在某些例程中,一旦知道了答案,就希望立即将其返回给调用例程。如果例程以不需要任何清理的方式定义,则不立即返回意味着必须编写更多代码。

其他回答

你知道有句谚语——情人眼里出西施。

有些人信得过NetBeans,有些人信得过IntelliJ IDEA,有些人信得过Python,有些人信得过PHP。

在一些商店,如果你坚持这样做,你可能会丢掉工作:

public void hello()
{
   if (....)
   {
      ....
   }
}

这个问题完全是关于可见性和可维护性。

I am addicted to using boolean algebra to reduce and simplify logic and use of state machines. However, there were past colleagues who believed my employ of "mathematical techniques" in coding is unsuitable, because it would not be visible and maintainable. And that would be a bad practice. Sorry people, the techniques I employ is very visible and maintainable to me - because when I return to the code six months later, I would understand the code clearly rather seeing a mess of proverbial spaghetti.

嘿,伙计(就像一个前客户曾经说过的),做你想做的,只要你知道如何在我需要你解决它的时候解决它。

I remember 20 years ago, a colleague of mine was fired for employing what today would be called agile development strategy. He had a meticulous incremental plan. But his manager was yelling at him "You can't incrementally release features to users! You must stick with the waterfall." His response to the manager was that incremental development would be more precise to customer's needs. He believed in developing for the customers needs, but the manager believed in coding to "customer's requirement".

我们经常因为打破数据规范化、MVP和MVC边界而感到内疚。我们内联而不是构造函数。我们走捷径。

就我个人而言,我认为PHP是一种糟糕的实践,但我又知道什么呢?所有的理论争论都归结为试图满足一套规则

质量=精度,可维护性 和盈利能力。

所有其他规则都退居幕后。当然,这条规则永远不会消失:

懒惰是一种美德 程序员。

Structured programming says you should only ever have one return statement per function. This is to limit the complexity. Many people such as Martin Fowler argue that it is simpler to write functions with multiple return statements. He presents this argument in the classic refactoring book he wrote. This works well if you follow his other advice and write small functions. I agree with this point of view and only strict structured programming purists adhere to single return statements per function.

正如Kent Beck在《实现模式》中讨论保护子句时指出的那样,使一个例程具有单一的入口和出口点……

是为了防止可能的混淆 当你在许多地方跳来跳去 同一例程中的位置。这让 当应用到FORTRAN或 汇编语言程序 有大量的全球数据,甚至 理解哪些语句是 执行是一项艰苦的工作……使用小方法和大部分本地数据,它是不必要的保守。”

我发现用保护子句编写的函数要比一长串嵌套的if then else语句容易理解得多。

拥有多个出口点本质上与使用GOTO是一样的。这是不是件坏事取决于你对迅猛龙的看法。

这主要是Fortran的遗留问题,在Fortran中,可以将多个语句标签传递给一个函数,这样函数就可以返回其中任何一个。

所以这种代码是完全有效的

       CALL SOMESUB(ARG1, 101, 102, 103)
C Some code
 101   CONTINUE
C Some more code
 102   CONTINUE
C Yet more code
 103   CONTINUE
C You get the general idea

但是被调用的函数决定了你的代码路径。有效率呢?可能。可维护的?不。

这就是该规则的来源(顺便说一下,一个函数没有多个入口点,这在fortran和汇编程序中是可能的,但在C中不可能)。

然而,它的措辞看起来像是可以应用到其他语言(关于多个入口点的那个不能应用到其他语言,所以它不是一个真正的程序)。所以这条规则被保留了下来,即使它指的是一个完全不同的问题,而且不适用。

对于更结构化的语言,需要放弃这个规则,或者至少考虑更多。当然,一个充满返回值的函数很难理解,但在开始时返回不是问题。在一些c++编译器中,如果你只从一个地方返回一个值,那么一个返回点可能会生成更好的代码。

但是最初的规则被误解了,被误用了。也不再相关了。