Should all methods be static if their class has no member variables

前端 未结 20 2149
悲哀的现实
悲哀的现实 2020-12-02 14:18

I\'ve just had an argument with someone I work with and it\'s really bugging me. If you have a class which just has methods like calculateRisk or/and calc

相关标签:
20条回答
  • 2020-12-02 15:14

    I would avoid making these static. Whilst at the moment that may make sense, you may in the future want to add some behaviour. e.g. at the moment you would have a default calculation engine (strategy):

    CalcService cs = new CalcService();
    cs.calcPrice(trade, date);
    

    and later on you may want to add a new calculation engine:

    CalcService cs = new CalcService(new WackyCalculationStrategy());
    cs.calcPrice(trade, date);
    

    If you make this class instantiatable, then you can create different instances and pass them around, instantiate on the fly etc. You can give them long-running behaviour (e.g. how many calculations involving trade X has this object done ? etc.)

    0 讨论(0)
  • 2020-12-02 15:14

    if the methods need information in a Trade instance to do their work, then why aren't these methods non-static members of the Trade class?

    0 讨论(0)
  • 2020-12-02 15:15

    If you make it static, you can't inject a different implementation easily.

    There is no longer any runtime cost to calling non-static methods, so for new code avoid static as far as sensible.

    OTOH, refactoring tools can replace all calls to a static method fairly easily, so it's not critical one way or another.

    I don't know whether the calculation of prices or risks can vary in your domain. If there are different strategies, passing a stateless strategy implementation around may have benefits. But it's more code, and there's a good chance that YAGNI.

    0 讨论(0)
  • 2020-12-02 15:16

    I would say yes, but an argument could also be made in this case for just putting those methods on the Trade object.

    0 讨论(0)
  • 2020-12-02 15:20

    In my opinion they should be static. You might even get performance improvements because the compiler/jit might inline the methods

    0 讨论(0)
  • 2020-12-02 15:20

    In this case, I would probably make a couple of static methods. I would assume that the calc function does not depend upon other resources to calculate the values, and it is generally segregated from the rest of the code.

    In general, however, I tend to shy away from doing overly complicated things in static methods. If you were unit testing and wanted to swap in a MockCalcService, having the static calls spread out across your code would make it very difficult.

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