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?
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
The local variable may be returned to calling scope (the point in the program where the function was called), or it may be logged and discarded when the function ends.
return isn't like a function or a variable that gives you a value, it only takes values. You put it in a function, and whatever you return is what you get when you use the function later on. It's always the last thing a function does, when it returns, it stops executing.
Starting with C# 7.0, C# supports reference return values (ref returns). A reference return value allows a method to return a reference to a variable, rather than a value, back to a caller. The caller can then choose to treat the returned variable as if it were returned by value or by reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With