如果块"if"返回,我们是否需要"else"构造?

Kse*_*nia 1 java

我知道以下方法也是如此,但哪种变体更好,为什么?

public boolean method() {
      if (condition) {
          return otherMethod();
      } else {
          return true;
      }
}     
Run Code Online (Sandbox Code Playgroud)

要么

public boolean method() {
      if (condition) {
          return otherMethod();
      } 
      return true;
}  
Run Code Online (Sandbox Code Playgroud)

或许这是更好的变种?

public boolean method() {
     return condition ? otherMethod() : true;
}
Run Code Online (Sandbox Code Playgroud)

wvd*_*vdz 5

我对此有一个非常强烈的意见,即else在这种情况下使用块是一种糟糕的风格.

else一旦逻辑变得足够复杂,使用将极大地妨碍可读性.

例如:

if (cond1)
   then return
else
    // Do some processing
    if (cond2)
        then return
    else
         // Do some processing
         if (cond3)
             ....
Run Code Online (Sandbox Code Playgroud)

所以你最终得到一个深层嵌套的结构,这是完全没必要的,因为它等同于:

if (cond1)
   then return
// Do some processing
if (cond2)
   then return
// Do some processing
if (cond3)
   ....
Run Code Online (Sandbox Code Playgroud)