When to make a method static?

后端 未结 7 403
忘掉有多难
忘掉有多难 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

    It depends. In languages where non-member functions are possible I'd say that most of the time, if the method could be made static, it should be made a non-member function instead, non-friend if possible. You can tell I have a mostly C++ background.

    In "pure" OO languages where non-member functions are not possible it would depend on whether the method is only "incidentally" static (i.e. it just happens not to need access to instance members), or is truly logically static - it is a method of the whole class instead of for a particular instance.

提交回复
热议问题