Java风格与多个回报相关,用作“警卫”

时间:2016-06-22 19:28:20

标签: java coding-style

在Java社区中是否有一种思想流派 - 在方法中使用多个返回,如下所示:

public SomeClass someMethod(int someValue) {
    if (someValue < SOME_CONSTANT) {
        return null;
    }

    SomeClass someClass = null;
    // and now, the body of the method that performs
    //   the heavy lifting
    return someClass;
}

我在“单入口点,单出口点”的口号下“长大”,但我可以看到使用简单的警卫如何使代码更易读/可维护(即,消除嵌套级别)。 “单出口点”版本看起来像......

public SomeClass someMethod(int someValue) {
    SomeClass someClass = null;

    if (someValue < SOME_CONSTANT) {
        // and now, the body of the method that performs
        //   the heavy lifting
    }
    return someClass;
}

诚然,这是一个微不足道的例子,但我可以看到更多的先决条件会导致更大的嵌套。就我个人而言,我仍然坚持“不要在整个方法中洒水”用于其他目的(即,仅作为警卫的结果“返回”,或者在方法结束时),但我想知道如何其余的Java社区感受到了。

添加了“苹果示例”......

public Pie makeApplePie(Apple apple) {
    if (apple == null) {
        return null;
    }

    // do cool stuff with apple
    return new Pie();
}

1 个答案:

答案 0 :(得分:0)

除非你的逻辑强迫你,否则我绝对更喜欢单退出。有时可能会有一个for循环,其中你计算了你的结果,因此想要破解。 然后在for循环之后可能会有更多的语句,你不想执行但是马上返回然后你别无选择,只能有多个return语句

代码如下:

public  SomeClass myMethod()
{
   SomeClass sc = null;

   for ( int i = 0; i < (someCondition); i++ )
   {
      //computed result
      sc = result;
      return sc; //result is SomeClass
   }

   //Some more machinery to assign a value to sc

   return sc;
}