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

前端 未结 13 1500
暖寄归人
暖寄归人 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:18

    I would use an instance method by default. The advantage is that behavior can be overridden in a subclass or if you are coding against interfaces, an alternative implementation of the collaborator can be used. This is really useful for flexibility in testing code.

    Static references are baked into your implementation and can't change. I find static useful for short utility methods. If the contents of your static method are very large, you may want to think about breaking responsibility into one or more separate objects and letting those collaborate with the client code as object instances.

提交回复
热议问题