Tuesday, November 22, 2011

java Static methods vs singletons

From a strict runtime performance point of view, the difference is really negligible. The main difference between the two lies down in the fact that the "static" lifecycle is linked to the classloader, whereas for the singleton it's a regular instance lifecycle. Usually it's better to stay away from the ClassLoader business, you avoid some tricky problems, especially when you try to reload the web application.

You can find "some blogger" who pretty much dislikes anything. There's nothing wrong with static methods, so long as any state they operate on is local to the method/passed in with each call (same caveat applies for instance methods on a singleton).
Either approach should be fine, just pick the one you prefer. As a general rule of thumb, go with static methods if your singleton instance would not be holding any state that is potentially mutable at runtime. Otherwise, if the singleton is meant to hold state and not just serve as a repository for a handful of utility methods, then make it a singleton.
The only halfway reasonable argument against using static methods that I have come across is that static methods are problematic to mock-out for unit-testing purposes. But my guess is that you are probably not doing mock unit-testing, and I think the value of testing with mock objects is generally overstated when you look at the value that comes out of it relative to the amount of work that goes into setting up the test case(s).

No comments:

Post a Comment