Is there any benefit to returning the result of assigning a value to a local variable rather than the value directly?

拜拜、爱过 提交于 2020-05-23 12:06:09

问题


I am doing a java code inspection. Here is a function (snippet):

String getValue() {
     String res;
     StringBuilder strBuilder = new StringBuilder();

     // More code here that sets strBuilder

     return res = strBuilder.toString();
}

First there is a warning that the value of res is not used. Secondly I don't understand the return. Why don't they just return( strBuilder.toString() ). Is there some sort of advantage?


回答1:


res is not used, so there is no reason to return like that. You can remove it:

String getValue() {
     StringBuilder bs = new StringBuilder();
     //
     // More code here that sets sb

     return bs.toString();
}



回答2:


That sort of code can sometimes result from incomplete removal of debug artifacts:

String getValue() {

     String res;
     StringBuilder bs = new StringBuilder();
     //
     // More code here that sets sb

     res = bs.toString();
     // Test and/or display res here
     return res; 
}

It certainly seems like a good candidate for the next round of refactoring and clean-up.




回答3:


Just guessing, but some (most?) IDEs don't allow you to directly inspect the value of function returns. With this scheme, you could put a breakpoint at the end of the method, and mouse over "res" to get the return value.




回答4:


You're absolutely right; assignment to res makes no sense; return bs.toString(); would do the the same.


P.S. +1 for not ignoring compiler warnings.




回答5:


You cant do either

String res = strBuilder.toString();
return res ;

Or directly,

return strBuilder.toString();

Now If you want to know about benefits as you asked Is there any benefit, i always prefer directly return. My personal logic is simple as

  • You gonna write one line less code !!! (declaring variables allover is not a good feeling to me and also you don't have to think about the name of the variable, conflicts etc.. those silly matter )
  • The value will not be stored in memory and wait for the GC to collect it. SO, less memory see.....
  • Fast write to a variable and then read from it and return ..... more read/write isn't it?

Those things are nothing big, I had to say as you asked




回答6:


Can also be written as:

String getValue() {
    return new StringBuilder().toString();
}


来源:https://stackoverflow.com/questions/27994404/is-there-any-benefit-to-returning-the-result-of-assigning-a-value-to-a-local-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!