I am doing a java code inspection. Here is a function (snippet):
String getValue() {
String res;
StringBuilder strBuilder = new StringBuilder();
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.
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
GC
to collect it. SO, less memory see..... Those things are nothing big, I had to say as you asked
Can also be written as:
String getValue() {
return new StringBuilder().toString();
}
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();
}
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.
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.