Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 417
user3257891 Avatar asked Jan 16 '15 23:01

user3257891


People also ask

Why is it unsafe for a function to return a local variable by reference?

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.

Can local variables be returned?

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.

Can we assign value in return statement?

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.

How do you return a variable in C#?

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.


2 Answers

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();
}
like image 138
BackSlash Avatar answered Sep 22 '22 13:09

BackSlash


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.

like image 32
Patricia Shanahan Avatar answered Sep 21 '22 13:09

Patricia Shanahan