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

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

    I don't think any of the answers get to the heart of the OO reason of when to choose one or the other. Sure, use an instance method when you need to deal with instance members, but you could make all of your members public and then code a static method that takes in an instance of the class as an argument. Hello C.

    You need to think about the messages the object you are designing responds to. Those will always be your instance methods. If you think about your objects this way, you'll almost never have static methods. Static members are ok in certain circumstances.

    Notable exceptions that come to mind are the Factory Method and Singleton (use sparingly) patterns. Exercise caution when you are tempted to write a "helper" class, for from there, it is a slippery slope into procedural programming.

提交回复
热议问题