I think I’ve typed out three different replies for this, and erased them before hitting send…
Primarily, the danger with Singletons is found in the difficulty of unit testing and debugging code. There are also some race condition risks associated with Singletons. Hugo (@CodeMonkey) has done a great job dealing with the race condition issues.
There will always be disagreements about the use of Singletons. The debate is older than some of our students. To some, they’re the greatest thing since sliced buttered bread. To others, they are anathema – the downfall of coding and the end of the world!. I’d say that the truth is somewhere in between those extremes.
Hugo is absolutely right, it’s a tool. While some refer to it as an “Anti-pattern”, it is a real pattern that is as old as all the other design patterns associated with Object Oriented Programming. If you look in my workshop, you’ll find a lot of tools… screwdrivers, hammers, drills, saws, sanders, etc. If I need to cut some wood, I won’t get very far with a hammer. If I need to screw things together, my saw just doesn’t do the trick. That doesn’t mean that any of my tools are bad, just that they may not be the right tool for a particular task.
Don’t be afraid of Singletons, but do be aware of the issue… that as global state, something else may be changing data that may not be in your control. If you ever start Unit Testing, Singletons can wreak havoc on tests if they are not well managed.
Probably one of the biggest risk with Singletons is that sometimes users will take things a step further and use them as global data repositories with global access to everything… You’ll note we’re not doing that here. Data within the Singleton is still managed by the class itself. We might refer to the Singleton’s instance, but we’re reading fields and calling methods, not simply setting global variables. That particular issue: Setting public variables in a different class or object- that is the real problem at the heart of things, and you don’t even need to use Singletons to fall into that particular trap.
While personally, I avoid Singletons when I can, I do use them, and I’m certainly not going to say never use them. Be mindful. When you use a Singleton in your own code design, ask yourself why. Is there another approach you can take? Is that an easy approach, or a complicated one? Sometimes, if the fix is too compilicated, it really is easier to use a Singleton.