更好的Java方法语法?早退还是迟到? [英] Better Java method Syntax? Return early or late?

查看:246
本文介绍了更好的Java方法语法?早退还是迟到?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


重复: 函数是否只有一个return语句?


通常你可能有一个方法来检查多个条件并返回一个状态(现在让我们说布尔值)。最好定义一个标志,在方法中设置它,并在结束时返回:

  boolean validate ){
boolean valid = false;
if(o.property == x){
valid = true;
} else if(o.property2 == y){
valid = true;
} ...
return valid;
}

或者更好/更正确的一旦你知道方法的结果?

  boolean validate(DomainObject o){

if(o.property == x){
return true;
} else if(o.property2 == y){
return true;
} ...
return false;
}



现在显然可以有try / catch块和所有其他类型的条件,但我认为这个概念是清楚的。意见?

解决方案

如果这是一个方法,你会调用数千次, ]提高了性能。



如果没有,那么我更喜欢延迟退货,因为它提高了可读性。记住程序员通常比编写代码花费更多的时间阅读,所以任何能够提高可读性的方法都是值得欢迎的。


Duplicate: Should a function have only one return statement?

Often times you might have a method that checks numerous conditions and returns a status (lets say boolean for now). Is it better to define a flag, set it during the method, and return it at the end :

boolean validate(DomainObject o) {
  boolean valid = false;
  if (o.property == x) {
     valid = true;
  } else if (o.property2 == y) {
     valid = true;
  } ...
  return valid; 
}

or is it better/more correct to simply return once you know the method's outcome?

boolean validate(DomainObject o) {

  if (o.property == x) {
     return true;
  } else if (o.property2 == y) {
     return true;
  } ...
  return false; 
}

Now obviously there could be try/catch blocks and all other kinds of conditions, but I think the concept is clear. Opinions?

解决方案

If it's a method you'll be calling thousands of times, then early return is better to achieve a [slightly] increased performance.

If not, then I'd prefer late return, since it improves readability.

Remember programmers usually spend more time reading than writing code, so anything you can do to improve readability will be certainly welcome.

这篇关于更好的Java方法语法?早退还是迟到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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