December 20, 2009

Singularly Lazy

Tags: Technical

Ah, the Singleton pattern. It is used to create a single, globally accessible instance of a class, preventing any further instantiations (so only one object of the class can ever exist). When I first learnt about Singletons soon after leaving university, I thought they were wonderful and used them often. Now I think that they are often a very bad idea. Not because of security concerns, as one person once suggested to me, but because I don’t want static methods/classes hanging round (increasing global state) or I later realise more than one is needed!

Once when creating a consumer website for a bank I needed access to various pieces of bank information at numerous points in the code. “There is only one bank”, I reasoned and made the class containing this information a singleton. Then the bank acquired another two banks so my design was broken and refactoring had to take place right before launch. However, despite learning repeatedly from experience, I still find myself creating more. I think this is due to laziness on my part. If I’m short of time or feel that it is not particularly important, I fall back on habit. Later, while refactoring I realise a better result could have been achieved with some thought. For instance, if the global access of singletons is a problem, perhaps using an IoC container (like Spring) to wire everything up could help.

I hereby resolve not to use Singletons without thinking very hard first about whether there is a better way.