繁体   English   中英

返回语句在Java中的最佳做法?

[英]Return statement best practices in java?

我想知道这两个代码之间的区别,即使它们产生相同的输出:

代码1:

class ret {
    public static int add(int x) {
        if(x!=0)
            return x+add(x-1);
        return x;
    }

    public static void main(String args[]) {
        System.out.println(add(5));
    }
}

代码2:

class ret {
    public static int add(int x) {
        if(x!=0)
            return x+add(x-1);
        return 0;
    }

    public static void main(String args[]) {
        System.out.println(add(5));
    }
}

它们都输出15,但是第二个代码又为什么输出15而不是零呢?我的理解是最后一次调用将是代码2的add(0)并且将返回零。我还想知道可以使用倍数return语句或使用单个return语句并用局部变量替换其余部分。我记得阅读单入口单出口模型是一个好习惯。

这是一个递归方法,因此当x != 0 ,您将返回“ x添加到使用(x-1)再次调用该方法的结果”。 最终调用将始终返回x == 0constant = 0 ,因此您将同时从两个版本中返回15

单向收益与多向收益是一个辩论的问题。 通常应首选前者。 通常,可以接受多个return语句是很明显的,因为使用它们可以比使用单个出口点所需的替代代码构造更容易理解方法。 另请注意,您可以将add改写为:

public static int add(int x) {
    return x == 0 ? 0 : (x + add(x-1));
}

版本1:

add(5)
  call add(4)
    call add(3)
      call add(2)
        call add(1)
          call add(0)
          return (x = 0)
        return (x = 1) + (add(x-1) = 0) = 1
      return (x = 2) + (add(x-1) = 1) = 3
    return (x = 3) + (add(x-1) = 3) = 6
  return (x = 4) + (add(x-1) = 6) = 10
return (x = 5) + (add(x-1) = 10) = 15

版本2:

add(5)
  call add(4)
    call add(3)
      call add(2)
        call add(1)
          call add(0)
          return (constant = 0) // the only difference
        return (x = 1) + (add(x-1) = 0) = 1
      return (x = 2) + (add(x-1) = 1) = 3
    return (x = 3) + (add(x-1) = 3) = 6
  return (x = 4) + (add(x-1) = 6) = 10
return (x = 5) + (add(x-1) = 10) = 15

使用单行答案无法回答使用多个return语句还是使用单个出口点。 我猜您可以获得的最佳答案是“这取决于您公司的标准”。

即使我个人不认可单出口,这也是一个非常好的标准。 最终,您的方法的末尾总是只有一个return语句,因此,在编辑其他人的代码时,您永远不会处于寻找那么多可能的return语句的位置。 我相信曾经使用C进行编码的开发人员倾向于遵循此标准(请参阅此问题 )。

我可以使用多个return语句来简化代码。 我喜欢使用它的一种情况是防止在代码中级联括号。 例如,在以下示例中:

private int doSomething (int param) {
    int returnCode;

    if (param >= 0) {
        int someValue = param * CONSTANT_VALUE;

        if (isWithinExpectedRange (someValue)) {
            if (updateSomething (someValue)) {
                returnCode = 0;
            } else {
                returnCode = -3;
            }
        } else {
            returnCode = -2;
        }
    } else {
        returnCode = -1;
    }

    return returnCode;
}

我发现这种编码类型在阅读时非常混乱。 我倾向于将这种类型的代码更改为:

private int doSomething (int param) {
    if (param < 0) {
        return -1;
    }

    int someValue = param * CONSTANT_VALUE;

    if (!isWithinExpectedRange (someValue)) {
        return -2;
    }

    if (!updateSomething (someValue)) {
        return -3;
    }

    return 0;
}

第二个示例对我来说看起来更清晰。 当实际代码在else块中有一些额外的编码时,甚至更多。

同样,这是个人喜好。 有些公司可能会强制执行一个出口点,有些可能不会,并且某些开发人员更喜欢单个出口点。 底线是,如果有适合您的环境的指南,则可以这样做。 如果不是,那么您可以部分根据这些参数选择自己的偏好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM