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

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

提交回复
热议问题