Tuesday, January 8, 2013

The Singleton Considered Evil

Evil's a pretty strong word to attach to a Software Design Pattern but hopefully it grabbed your attention.

The Singleton pattern has come in for quite a kicking over the years and to me there seems to be 3 problems associated with it.

The first is overuse and particularly, use when not appropriate, e.g. when a static function would suffice or when there is no system resource that needs protecting in the first place. I've seen people wrap standard maths functions up into a Singleton...really! Talk about making life hard for the compiler...

The second is that it can hide global state thus making testing hard. Thus making reasoning about your program hard, I should say. This is explained nicely here (see about 4 mins 20 sec).

The third, actually the clincher for me, is that it breaks its own abstraction by not hiding the information that the class is a Singleton from its users...the user of any Singleton class couldn't give a fig thats it's a Singleton - all it really wants is the interesting operations that it is going to use when it gets hold of the Singleton object. The importance of information hiding can not be overstated, it might be a very 70's expression but some truths are as true today as they were then, see here.

The solutions to these problems? Well, the second and third can be solved by Dependency Injection (preferably into the constructor), where the dependency injected is to an interface but an interface that does not include the Singleton. If you still insist on using a Singleton, the testing problem can be alleviate by the rule of "Never use a Singleton on its own" [(c) On The Road To Tau], instead double it up as a Strategy Pattern, so you can replace the 'real' processing with mock test processing.

The first by teaching and (un)common sense...good luck with that!!