Books, tutorials and other design pattern featuring articles often tend to present the Singleton Design Pattern as the first one. This is for two reasons:
- The Singleton is a very easy to understand design pattern, even for developers new to design patterns or relatively new to the object oriented world.
- The Singleton solves a problem that 99% of these developers have, namely to provide a global access point to some class they make use of everywhere in their application.
However, the Singleton design pattern is fundamentally flawed. This is nothing new and is discussed amongst developers since some years now (just
search for "evil singleton"). The Singleton violates several rules of good object oriented design. Code using the Singleton class depends on that class. It is not usable without this class, which in turn makes the client code hard to test. The client code is not programmed against an interface but against a concrete class, though promoting tight coupling between the client and the Singleton, instead of the desired loose coupling. Additionally, classes implementing the Singleton pattern itself are hard to test. Singleton just replaces a global variable and hides it in a class - the global state stays in your application. So, when everybody agrees that global state is bad and that its appearance as Singleton implementations does not make the code any better, why is the Singleton design pattern so often used then?
Continue reading "How to get a Singleton right"