更好的方式从条件返回

时间:2015-08-07 13:37:52

标签: java conditional-statements

从条件返回哪种方式更好,就像process1和process 2一样。但我想知道更好的回归方式。 在这两种情况下,我都不想进入循环内部,我只想返回。我想知道,是否有任何性能差异如果我在控制传递到结束之前放回。我不希望Java虚拟机检查循环结束并从那里返回。我想如果当条件不满意时我立即返回,那么我可以看到较小的性能差异以及代码可读性。请建议我最好的方法。 让我们考虑以下情况。

Process1:

public Method()
{ //Method        
    Company company = new Company(); //Object
    if (null != Address && null = Address.location())  //Condition
    {
        return company; //I want to return
    }

        for (Location location: Address.location())
        {
            //forloop
        }

    return company; //return
}

过程2:

public Method()
{
    Company company = new Company();
    if (null != Address && null != Address.location()) 
    {
            //enters loop
    }
    return company; // return
}

1 个答案:

答案 0 :(得分:-1)

会有一些性能影响。从for循环中迭代完整对象以验证条件。

For example:

We can write like this.
if(condition is false){
  return ;
else{

   for(DataType ref: collection){
      if(true){
         return;// return from here, so that it will not iterate remaining elements.
      }
   } 
}


ex 2: 

if there is a logic after the if and that should not be executed, if the object is null.

if(object is null){

  return ;
}

//Remaining logic here will not be executed, if the object is null. it's a good way of writing.


ex 3: 

if there is no logic after the if and else, then directly return from the end of method.

if(object is null){
   return 
}else{
   //process logic and return. 
}

you can write something like this.

if(object is not null){
 // return either from here.
}
return here is also fine...
相关问题