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

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


当前回答

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

有些人信得过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是一种糟糕的实践,但我又知道什么呢?所有的理论争论都归结为试图满足一套规则

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

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

懒惰是一种美德 程序员。

其他回答

我使用多个出口点使错误情况+处理+返回值尽可能接近。

所以必须测试条件a, b, c必须为真,你需要用不同的方式处理它们:

if (a is false) {
    handle this situation (eg. report, log, message, etc.)
    return some-err-code
}
if (b is false) {
    handle this situation
    return other-err-code
}
if (c is false) {
    handle this situation
    return yet-another-err-code
}

perform any action assured that a, b and c are ok.

a, b和c可能是不同的东西,比如a是输入参数检查,b是新分配内存的指针检查,c是检查参数a中的值。

我想说,武断地决定不使用多个出口点是非常不明智的,因为我发现这种技术在实践中一次又一次地有用,事实上,为了清晰起见,我经常将现有的代码重构为多个出口点。我们可以这样比较这两种方法:-

string fooBar(string s, int? i) {
  string ret = "";
  if(!string.IsNullOrEmpty(s) && i != null) {
    var res = someFunction(s, i);

    bool passed = true;
    foreach(var r in res) {
      if(!r.Passed) {
        passed = false;
        break;
      }
    }

    if(passed) {
      // Rest of code...
    }
  }

  return ret;
}

将此与允许多个出口点的代码进行比较

string fooBar(string s, int? i) {
  var ret = "";
  if(string.IsNullOrEmpty(s) || i == null) return null;

  var res = someFunction(s, i);

  foreach(var r in res) {
      if(!r.Passed) return null;
  }

  // Rest of code...

  return ret;
}

我认为后者要清楚得多。据我所知,现在对多个退出点的批评是一种相当过时的观点。

你可以这样做,只实现一个返回语句-在开始时声明它,在结束时输出它-问题解决了:

$content = "";
$return = false;

if($content != "")
{
  $return = true;
}
else 
{
  $return = false;
}

return $return;

我强迫自己只使用一个return语句,因为在某种意义上它会产生代码气味。让我解释一下:

function isCorrect($param1, $param2, $param3) {
    $toret = false;
    if ($param1 != $param2) {
        if ($param1 == ($param3 * 2)) {
            if ($param2 == ($param3 / 3)) {
                $toret = true;
            } else {
                $error = 'Error 3';
            }
        } else {
            $error = 'Error 2';
        }
    } else {
        $error = 'Error 1';
    }
    return $toret;
}

(条件是任意的…)

条件越多,函数越大,读取起来就越困难。因此,如果您熟悉代码气味,您就会意识到它,并想要重构代码。两种可能的解决方案是:

多的回报 重构为单独的函数

多的回报

function isCorrect($param1, $param2, $param3) {
    if ($param1 == $param2)       { $error = 'Error 1'; return false; }
    if ($param1 != ($param3 * 2)) { $error = 'Error 2'; return false; }
    if ($param2 != ($param3 / 3)) { $error = 'Error 3'; return false; }
    return true;
}

单独的功能

function isEqual($param1, $param2) {
    return $param1 == $param2;
}

function isDouble($param1, $param2) {
    return $param1 == ($param2 * 2);
}

function isThird($param1, $param2) {
    return $param1 == ($param2 / 3);
}

function isCorrect($param1, $param2, $param3) {
    return !isEqual($param1, $param2)
        && isDouble($param1, $param3)
        && isThird($param2, $param3);
}

当然,它会更长,而且有点乱,但在以这种方式重构函数的过程中,我们已经

创建了许多可重用的函数, 使函数更具人类可读性,以及 函数的重点在于为什么值是正确的。

如果你最终得到了很多返回值,那么你的代码可能有问题。否则,我同意有时能够从子例程的多个位置返回是很好的,特别是当它使代码更干净的时候。

Perl 6:坏例子

sub Int_to_String( Int i ){
  given( i ){
    when 0 { return "zero" }
    when 1 { return "one" }
    when 2 { return "two" }
    when 3 { return "three" }
    when 4 { return "four" }
    ...
    default { return undef }
  }
}

这样写会更好吗

Perl 6:好例子

@Int_to_String = qw{
  zero
  one
  two
  three
  four
  ...
}
sub Int_to_String( Int i ){
  return undef if i < 0;
  return undef unless i < @Int_to_String.length;
  return @Int_to_String[i]
}

注意,这只是一个简单的例子