Singletons and evil

In a comment a while ago, David wanted to know why are Singletons the root of all evil. Well, that’s just because they are!

Ok, it is not that easy. Nor that black-and-white, either. Let’s see if I can articulate some of the reasons why Singletons are bad for you and for your code.

From all the varieties of pattern abuse out there, singletonitis is the most irritating one because of two simple reasons:

  1. Singleton is one of the patterns with the worst side effects.
  2. Singleton abuse is one of the most widespread varieties of pattern abuse.

In 99% of Singleton occurrences, the Singleton pattern was unnecessarily introduced with one of the following excuses:

  • Some object needs to access a resource that isn't available in that abstraction layer. The right solution to this problem is to redesign. Solving bad design by throwing a pattern at it just makes things worse.
  • As a glorified global variable. Global variables can be avoided most of the time, and they should be avoided wherever possible. See previous point on solving bad design by layering patterns on top.
  • Premature optimization ("we shouldn't instantiate this more than once, or it will bring down performance; let's singletonize it!"). Thousands of wise words have been written on the evils of premature optimization, so I won't go into that here.

So it all boils down to the following: in most cases, programmers introduce Singletons either as a misguided attempt to improve a bad design, or as a means for premature optimization.

Singletons not only have the noxious effect of obscuring how objects collaborate, but they also hamper dependency injection, which in turn makes testing and refactoring extremely difficult. Thus, Singletons lead you into a spiral of unmaintainability. To think that they were unnecessary in the first place!

Tags: tech

« Older entries · Newer entries »