问题
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