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

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

    It is a tough call. Remember what Josh Bloch says about APIs:

    APIs, like diamonds, are forever. You have one chance to get it right so give it your best.

    (This may not be a public API, but if you have colleagues that are going to use this code, it effectively is an API.) If you declare those methods static, you constrain their future evolution, and incorporating state in the class will be difficult or impossible. You are going to have to live with those static method signatures. If you decide to make them non-static down the road because you need state, you are going to break the client code. I would say, when in doubt, don't make them static. That said, there is a place for static utility classes that contain a bunch of functions (e.g. calculate the area of a circle.) Your class may fall into that category.

提交回复
热议问题