When to make a method static?

后端 未结 7 531
忘掉有多难
忘掉有多难 2021-01-30 02:04

I\'d like to know how people decide whether to define a method as static. I\'m aware that a method can only be defined as static if it doesn\'t require access to instance fields

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 02:54

    I use static methods whenever I can. Advantages:

    • When calling a static method from inside an instance method, you can be sure that there are no side-effects on the state of the current object.
    • From inside a static method, you can be sure you don't accidentally modify any state of the object instance.
    • You can use a static method from outside the class without constructing an instance. If it was possible to make the method static, it clearly doesn't need an instance, so there's no need to require one.
    • Static methods may be slightly more efficient because no "this" pointer needs to be passed, and no dynamic dispatch is necessary.

提交回复
热议问题