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

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

    If the implementation of a method can be expressed completely in terms of the public interface (without downcasting) of your class, then it may be a good candidate for a static "utility" method. This allows you to maintain a minimal interface while still providing the convenience methods that clients of the code may use a lot. As Scott Meyers explains, this approach encourages encapsulation by minimizing the amount of code impacted by a change to the internal implementation of a class. Here's another interesting article by Herb Sutter picking apart std::basic_string deciding what methods should be members and what shouldn't.

    In a language like Java or C++, I'll admit that the static methods make the code less elegant so there's still a tradeoff. In C#, extension methods can give you the best of both worlds.

    If the operation will need to be overridden by a sub-class for some reason, then of course it must be an instance method in which case you'll need to think about all the factors that go into designing a class for inheritance.

提交回复
热议问题