In my talk about "Complex Projects with Cocoa" at a German iOS and OS X developer conference I warned the audience about the singleton design pattern. This warning resulted in something that I would call a small flame war about singletons. Although I have nothing against controversial discussions I was a bit surprised that many people tried to defend the singleton design pattern. For the rest of the conference I asked myself two simple questions:
- Why are so many people defending the singleton design pattern?
- How can these people be convinced that they are defending bullshit?
I will try to answer them both.
Why are so many people defending the singleton design pattern?
I think this is because the singleton design pattern is easy to understand. Most books and tutorials about design patterns first demonstrate the singleton pattern before anything else. So, every developer knows and understands the singleton design pattern. If this wouldn't be enough a singleton is often used by beginners to solve basic problems.
"I don't know how to pass an array from instance to instance. What do I do?"
Five minuted pass.
"Ah! LETS MAKE A SINGLETON!"
Another five minutes later and the poor developer has a singleton that holds the array of objects that can and will be access from everywhere. This makes the developer happy. He used a singleton to (superficially) solve a problem. One does not like to abandon something familiar. We all know that.
How can these people be convinced that they are defending bullshit?
Yes, there are singletons that make sense. No, I don't repeat what makes singletons so bad. So how do I convince you? Simply by quoting Erich Gamma. In an interview Erich Gamma, one of the authors of the famous book "Design Patterns: Elements of Reusable Object-Oriented Software", was asked the question "How would you refactor "Design Patterns?".
"[...] When discussing which patterns to drop, we found that we still love them all. (Not really—I'm in favor of dropping Singleton. Its use is almost always a design smell.) [...]"
This should convince everybody.