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

前端 未结 20 2343
悲哀的现实
悲哀的现实 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.)

提交回复
热议问题