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.

  • http://www.jordanzimmerman.com Jordan Zimmerman

    “you’ll need to go in and modify that object”. Changing the dependency via IoC _IS_ changing code. There is no semantic difference.

  • http://redsolo.blogspot.com redsolo

    I hate singletons because the code that uses the pattern is lying about their dependencies. Its like “hey, you can use me as I dont require any other objects to work”, but then when you start using its like “oh, sorry dude you must jump through this hoop, and fix up this and that class to use me”.

    I hate liars.