Java最好的风格为return语句 - 内部或外部if条件? [英] Java best style for return statement - inside or outside if condition?

查看:306
本文介绍了Java最好的风格为return语句 - 内部或外部if条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来编写下面的代码?我检查一个对象是否为null,返回false如果是,否则我检查另一个变量,并根据这个选择做什么。

Is there a better way to write the code below? I'm checking if an object is null, returning false if it is, otherwise I check another variable and choose what to do based on that.

private boolean myFunction(MyObjectType myObject) {
  if (myObject == null) {
    return false;
  } else if (myInstanceVariable.myMethod()) {
    // Do something then return
    System.out.println(myObject.getSomeValue());
    return true;
  } else {
    return false;
  }
}

return false (以及我可能已经在最后的 else {} 块之前放置的任何其他代码) if语句?我可以看到它是更安全的(和更少的代码行)将其移到外面,所以函数是100%保证返回。

Is it better to have the final else statement or move the return false (and any other code that I may have put before it inside the final else { } block) outside the if statement? I could see it being safer (and fewer lines of code) to move it outside so the function is 100% guaranteed to return. Could it depend on how the compiler behaves?

private boolean myFunction(MyObjectType myObject) {
  if (myObject == null) {
    ...
  } else if (myVariable.myMethod()) {
    ...
  }
  return false;
}


推荐答案

private boolean myFunction(MyObjectType myObject) {
  if (myObject == null) {
    return false;
  }
  if (myInstanceVariable.myMethod()) {
    // Do something then return
    System.out.println(myObject.getSomeValue());
    return true;
  }
  return false;
}



如果您从 code> block,那么你不需要 else 块。我发现它更好,因为逻辑的真正复杂性更好地表达这个较不复杂的看法。较少的大括号和较少的缩进使其更容易理解,至少对我来说。

If you are returning from inside an if block, then you don't need an else block. I find it better because the true complexity of the logic is better expressed by this less-complex looking method. Fewer braces and less indentation makes it easier to understand, at least for me.

这篇关于Java最好的风格为return语句 - 内部或外部if条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆