Modify method parameter within method or return result

前端 未结 7 2394
余生分开走
余生分开走 2020-12-05 02:47

What is the difference between

private void DoSomething(int value) {
    value++;
}

and

private int DoSomething(int value)          


        
7条回答
  •  攒了一身酷
    2020-12-05 03:10

    Return a value.

    Why?

    Correctness, Readability, and Self-Documentation

    Intentional and easy to understand code is better than side-effect code. Consider:

    float area = pi * Square(r);
    

    vs.

    Square(r);
    float area = pi * r;
    // ... intervening code
    float x = r * 5;  // did you mean to use the original r or r-squared here?
    

    Also consider the advantages of terseness through composability in the first example.

    Consider the methods themselves, compare:

    int DoSomething(int value)
       { return value+1; }
    

    Which is pretty obviously correct. vs.

    void DoSomething(int value)
       { value++; }
    

    Which seems right and will compile just fine but is actually just a no-op. What you really want is this:

    void DoSomething(ref int value)
       { value++; }
    
    // client code:
    DoSomething(ref a);
    

    Variables are Cheap

    Many well-named variables is preferable over few reused general purpose variables. Resist the temptation to prematurely optimize, the chance that you will need to cut down on the number of local variables to improve the performance of your system is cosmically tiny. Again, Variables are Cheap, DON'T REUSE VARIABLES!

    Testability

    Consider:

    Assert.IsTrue(Square(2) == 4);
    

    vs.

    float a = 2;
    Square(a);
    Assert.IsTrue(a == 4);
    

    There are many other advantages to avoiding mutation in preference to returning a value. It's not merely an accident that mathematics defines a function as a mapping of input values to output values.

提交回复
热议问题