When to make a method static?

后端 未结 7 405
忘掉有多难
忘掉有多难 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 03:06

    Kevin Bourrillion wrote an insightful answer on this topic some time ago (admittedly from a Java perspective, but I think it's applicable to other languages too).

    He argues that you should basically only use static methods for pure functions.

    A "pure function" is any method which does not modify any state and whose result depends on nothing but the parameters provided to it. So, for example, any function that performs I/O (directly or indirectly) is not a pure function, but Math.sqrt(), of course, is.

    I tend to agree. (Although in my own code, traditionally, I've probably used way too many static helper methods all over the place... :-P And this surely has made code that uses those methods harder to test.)

    0 讨论(0)
提交回复
热议问题