Away with singletons
The Gang of Four published a catalog of design patterns that made approaches to common tasks in object-oriented programming widely known. Singleton is certainly among the best-known patterns. It ensures that only one instance of a given class exists. I don't know whether its popularity comes from how easy it is to understand or because everyone needs it (or at least thinks they do). In any case, you'll find singletons everywhere. Unfortunately, using the Singleton pattern comes with considerable risks and drawbacks. For me, those are testing and coupling between objects. Admittedly, that isn't a fault of the pattern itself so much as of using it in the wrong places.

Let's get to the root of the problem. A singleton by its nature holds some context. That's why we introduce it. A tip to start with: If you find a singleton in the code that holds no context, you have a great opportunity to remove that singleton behavior because it's unnecessary. Through the context we reach other parts of the system (service locator), such as cached data or a database connection pool. That still isn't a problem. The trouble starts when you nest singletons in each other. The application becomes one big, wired-together ball of mud.
We know the problem. Do we know the solution? In my experience the best solution is inversion of control implemented through dependency injection. Dependency injection doesn't eliminate singletons themselves. It lets you move them out of the application code and into the framework layer. That's exactly the point. A cleanly written application shouldn't use any singleton besides the one that serves as its entry point. A typical example is a framework singleton that takes control when an HTTP request comes in. In a desktop application, it's the singleton serving as a service locator through which the application obtains its controllers.
Related articles
Related CZ Podcast episodes
- #261 · Leadership
On leading people and teams. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio