是否有充分的理由说明在函数中只有一个return语句是一个更好的实践?
或者在逻辑上正确的情况下,可以从函数中返回,这意味着函数中可能有许多返回语句?
是否有充分的理由说明在函数中只有一个return语句是一个更好的实践?
或者在逻辑上正确的情况下,可以从函数中返回,这意味着函数中可能有许多返回语句?
当前回答
在其他条件相同的情况下,单一出口点可以显著提高代码的可读性。 但有一个问题:流行的结构
resulttype res;
if if if...
return res;
是假的,“res=”不比“return”好多少。它只有一个return语句,但函数实际结束的地方有多个点。
如果你的函数有多个返回值(或“res=”s),最好将它分解成几个较小的函数,每个函数都有一个退出点。
其他回答
如果管理得当,多次退出是件好事
第一步是明确退出的原因。我的通常是这样的: 1. 不需要执行函数 2. 发现错误 3.提前完成 4. 正常完成 我想你可以把“1”归为一类。不需要执行函数“into”3。提前完成”(如果你愿意的话,可以说是非常提前完成)。
第二步是让函数外部的人知道退出的原因。伪代码看起来像这样:
function foo (input, output, exit_status)
exit_status == UNDEFINED
if (check_the_need_to_execute == false) then
exit_status = NO_NEED_TO_EXECUTE // reason #1
exit
useful_work
if (error_is_found == true) then
exit_status = ERROR // reason #2
exit
if (need_to_go_further == false) then
exit_status = EARLY_COMPLETION // reason #3
exit
more_work
if (error_is_found == true) then
exit_status = ERROR
else
exit_status = NORMAL_COMPLETION // reason #4
end function
显然,如果将上图中的一大块工作移到一个单独的函数中是有益的,那么您应该这样做。
如果您愿意,您可以使用更具体的退出状态,例如,使用几个错误代码和早期完成代码来精确定位退出的原因(甚至位置)。
即使您强制这个函数只有一个出口,我认为您仍然需要指定出口状态。调用者需要知道是否可以使用输出,这有助于维护。
唯一重要的问题是“如何使代码更简单、更易读、更容易理解?”如果使用多个返回会更简单,那么就使用它们。
你知道有句谚语——情人眼里出西施。
有些人信得过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是一种糟糕的实践,但我又知道什么呢?所有的理论争论都归结为试图满足一套规则
质量=精度,可维护性 和盈利能力。
所有其他规则都退居幕后。当然,这条规则永远不会消失:
懒惰是一种美德 程序员。
拥有多个出口点本质上与使用GOTO是一样的。这是不是件坏事取决于你对迅猛龙的看法。
函数中return语句越多,该方法的复杂性就越高。如果您发现自己想知道是否有太多的return语句,那么您可能需要问问自己,该函数中是否有太多的代码行。
但是,不是,一个/多个返回语句并没有错。在某些语言中,这是一种比其他语言(C)更好的实践(c++)。