Design Patterns – Is Singleton pattern evil?

To hell with everything. Why the hell use singleton or even why the hell it is described as a pattern by GOF?

I don’t know. I have been reading, studying and even trying to code and use the same design patterns in real life. The very first and easy to understand pattern is Singleton. This pattern was defined/recognised/identified as a pattern which assures creation of one and only object throughout the life cycle of a program. Common or say classic example given is error logging mechanism. And that’s the only real world example. Rest of the examples such as file or database handles are not suitable examples. They can be said as good example but not perfect.

Why singleton is evil?

I don’t want to reinvent wheel. There are n number of reasons. The reason I found is, tight coupling. Coupling in OOPS or even Software Development is discouraged. Loosely coupled systems allow more robust testing. You can replace the modules with dummy modules, equivalent modules and test the system. In this scenario a file logging mechanism is a perfect example of singleton pattern. The mechanism can be file logger, database logger or any other logger and will not affect our system if we replace it. Coz its not tightly coupled to system. Or as I read some where it simply “gets” the information and doesn’t “set” anything in our system. On the other side a database layer can’t be singleton pattern. What if I replace my MySQL layer with PGSQL? The system may not perform as expected or worst may break.

I suggest using singleton pattern shamelessly if your system is going to be a very tightly coupled and is custom and specific to a requirement. My argument is performance counts more than portability. Ofcourse Bullet 350 is no match to Splendor and Splendor is no match to Bullet 350. So, singletons are evil but so is fire, if you use it to burn your neighbour’s house. Use fire to light up. Use singleton wisely. šŸ™‚

Author: Kumar Chetan Sharma

Run of the mill developer.