I came across a very good blog article today at http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/. It’s about Singleton Pattern.
I was not surprised at the title “Why I hate: Patterns” since like any man made creation, they have their own share of weaknesses. The author has made five points in support of his argument, he says:
- Singleton hides dependencies.
- Singletons are hard to test
- Singleton can’t be sub-classed (easily)
- Singleton is a lie (from Java Perspective)
- The system might evolve to need more instances of an object, whose only one instance is needed in current perspective.
Alright, first three points are fair. But are they really problems? I don’t think so, Singletons are meant to encapsulate the objects that are needed through out the system (e.g. a database connection). So it should be understood that (almost) all of the classes in the system would be using this resource.
About hard to test, well I am confused about it. The author says that singletons hide coupling and therefore make it hard to run tests. Well, may be, but I have not run into such a situation yet (and I immediately admit that I consider myself a beginner with patterns).
Well, yeah Singletons are hard to subclass. This is a genuine problem.
The last two points are not fair. If a platform sucks at supporting patterns, it’s not the pattern’s fault. (No offense to Java, but that seems as if MS were to blame JavaScript for having buggy implementation in their browser, would that have been fair.?)
Lastly, if I don’t foresee how the system would evolve and have used a Singleton where it should not have been, it’s a fault that I am responsible for. I should not have used singleton in first place. It’s the architects job to use the patterns right.
Conclusion:
Singleton pattern, as I said earlier, is meant to encapsulate global resources. It has become a convention to use Singletons for (at least) logging and DB Connections, which is, what Singletons are meant for. Having a couple of Singletons (for global resources) in the system won’t do any harm. But if you have stuffed your system with them, then there’s trouble and I guess that’s what Miller’s (author’s) article is addressing, but may be it’s not appropriately named.
————
[EDIT] The post was originally titled “Singletons are Evil? But why?”, however, it has been changed based on the discussion below…