On Cedric’s latest entry he complains about statics, and quite rightly. However, one of the commentators missed the point.
The comment was:
What’s the difference between storing command line parameters in static variables and ensuring that the statics get reinitialised each time your program is invoked and storing them in a singleton class and ensuring that the singleton gets reinitialised each time your program is invoked?
A singleton class has all the disadvantages of statics.
The point that the (anonymous) commentator misses is that Singletons and statics are not the same. Singleton is a creational pattern; it’s a design technique to ensure that there is only one instance. static, on the other hand, is something I’ve loosely dubbed an access pattern (though it’s really a technique). One can (and should) have Singletons, that aren’t static, and you can, if you work at it, have statics that aren’t Singletons,
The difference here is that with a Singleton, if you choose to no longer have a Singleton, it is easy to change. Typically the object that is the Singleton shouldn’t know it is one; it’s just a plain object, after all. Thus, configuration parameters (to borrow Cedric’s example) can be easily changed for another invocation of the object. In Cedric’s example, the right thing to do (as I’m sure he would agree) is to copy the parameters in the main() method into an instance of the object and execute that.
One of the strong anti-patterns in Java is the constant abuse of statics to hold state that really should be dynamic. Avoiding overuse of statics will generally give you a more flexible design.
Some good uses of statics, while I’m at it:
- obtaining constants
- factory methods (including the ubiqituous getInstance()!)
- stateless methods (though this can often live better in their own class)