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

前端 未结 6 1081
死守一世寂寞
死守一世寂寞 2021-01-17 09:01

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

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

         


        
相关标签:
6条回答
  • 2021-01-17 09:27

    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.

    0 讨论(0)
  • 2021-01-17 09:28

    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

    0 讨论(0)
  • 2021-01-17 09:42

    Can also be written as:

    String getValue() {
        return new StringBuilder().toString();
    }
    
    0 讨论(0)
  • 2021-01-17 09:48

    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();
    }
    
    0 讨论(0)
  • 2021-01-17 09:53

    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.

    0 讨论(0)
  • 2021-01-17 09:53

    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.

    0 讨论(0)
提交回复
热议问题