Is there a rule of thumb for when to code a static method vs an instance method?

前端 未结 13 1523
暖寄归人
暖寄归人 2021-02-04 17:19

I\'m learning Java (and OOP) and although it might irrelevant for where I\'m at right now, I was wondering if SO could share some common pitfalls or good design practices.

13条回答
  •  星月不相逢
    2021-02-04 18:05

    IMHO, if you can make it a static method (without having to change it structure) then make it a static method. It is faster, and simpler.

    If you know you will want to override the method, I suggest you write a unit test where you actually do this and so it is no longer appropriate to make it static. If that sounds like too much hard work, then don't make it an instance method.

    Generally, You shouldn't add functionality as soon as you imagine a use one day (that way madness lies), you should only add functionality you know you actually need.

    For a longer explanation...

    http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It

    http://c2.com/xp/YouArentGonnaNeedIt.html

提交回复
热议问题