When to make a method static? [closed]
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. So let's say we have a method that does not access instance fields, do you always define such a method as static, or only if you need to call it statically (without a reference to an instance).
Perhaps another way of asking the same question is whether you use static or non-static as the default?
Solution 1:
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.
Solution 2:
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.)
Solution 3:
If what the method does depend solely on its arguments, you can make it static. If the method does not instantiate any other of your user defined classes, you can make it static. The default, though, is to have it as non-static.