Tuesday, January 13, 2009

Essential Software Concepts: Static methods

Static methods is a common functionality in many languages. Whereas instance methods work on instantiated objects, static methods work on types or instantiated objects.


The big question is - when is it appropriate to use static methods? 

 

First the naive positives. These are the positives that often comes up, but which aren't really true.

  • Makes it more obvious which methods works on internal state. If it doesn't have state, it should be static.
  • Great for Factory Methods (See real negative).

 

And then the real pros and cons:

Real positive

  • Don't need to initialize an object. This can be good in the case of small and discrete methods. Some utility classes are good examples, for instance Math.
  • Can be good for simple and effective, fire and forget functions.

Real negative

  • Is hard to refactor away from.
  • Doesn't work with inheritance, polymorphism and interfaces.
  • Makes it hard to test (Some test-frameworks can). For those that can't it's impossible to mock the behavior, since there is no natural way of substituting the implementation at runtime.
  • Static Factory Methods makes implementers bound to the concrete implementation. Impossible to replace during test. Handling object graph wiring this way makes it even worse.
  • Simple static methods can evolve into larger (still, possibly, untestable) beasts, which are not only a hassle to refactor away from, but do they really give the advantage of risking it?

 

What you potentially can read from a static method

  • Unless global state exists, the static method can only work on the input parameters. It is often more natural to move the method to one of these. Remember to keep logic as close to where it belongs as possible.

Just a note. Untestable in the points above isn't necessarily true. I'm talking about the possibility of switching implementations with stubs/mocks to be able to isolate what we are testing. It depends what dependencies it has of course.

 

There is use for static methods. Just be sure that it outweighs the potential negative issues!

No comments: