Why I Hate Classical Singletons
Recently a colleague asked me why I’m so against using singletons… why do I think they’re so bad. The answer is quite simple… when you use a singleton you’re essentially saying that your object accepts this dependency and only this dependency, it will take no substitutes. Since the dependency isn’t substitutable, it’s difficult to swap it out with a different dependency without modifying the code.
This is a direct violation of the Open/Closed principle, and ensures that whenever behavior needs to be changed you’ll need to go in and modify that object. By favoring IoC over using a singleton you can make it easy to swap the dependency for something else to change the behavior.
Of course, this is what I call the “classical singelton pattern” … you access it via something like
FooBar foo = FooBar.getInstance();
That’s bad in more ways in one. However, a lot of times singletons are used because developers wish to have one and only one instance of an object used throughout the application. IoC supports this because you have control over how many instances are created and wired throughout the application, and frameworks like Spring and Guice create singleton scoped beans by default. But make no mistake, even without any kind of injection framework I’d still use dependency injection over singletons any day.