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:

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

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 »