Tuesday, July 28, 2009

Singletons can be dangerous

A dangerous pattern

Even a shallow internet research can quickly indicate the existence of many popular misconceptions regarding the singletons, [A1,A2,A3] which can easily mislead the software developers to inappropriate use of this pattern. Since the singleton pattern has several disadvantages and side-effects, misusing it creates much more problems than it is supposed to solve. Hence, before starting to use singletons in your code, it will be quite beneficial to study first some of the links provided at the end of this text, in order to fully understand when it is appropriate to use this pattern and be aware of the consequences of its usage. To give you a preview of what you are going to find out, I briefly present here some common misconceptions regarding the singletons and also a typical example of an inappropriate singleton usage.

Common misconceptions

  • The authors of the notable "Design Patterns" book [A1] recommend the use of singletons. (No they don't, [B6] they just present the singleton pattern in their book.)
  • When only one instance of a particular object is needed, then it is a good idea to implement this object as a singleton. (Not good enough reason. [A3])
  • Singletons do not share the same problems that global variables have. (They actually share most of them. [A3])

In case any of the above misconceptions does not seam obvious to you, you definitely need to do some more reading, in order to be more familiar with the disadvantages and side-effects of the singleton pattern.

Example of inappropriate usage

A typical example of an inappropriate singleton is a singleton, which is merely being used by a single class or function. There are at least two good reasons for not using this pattern in such cases:

  • Singletons are essentially globals. Hence in case only a single class or function is using a particular singleton, then this singleton object has much larger scope and lifetime than its actual usage requires. This is obviously a bad practice, even by the standards of the old fashion structured programming. In other words, its not wise to use a global, when a local variable is sufficient enough.
  • Singletons have been designed to work well in cases when their potential creators, owners and clients are many in number and also hard to predict. In such cases the use of a singleton effectively eliminates most of the problems caused by the nondeterministic creation and ownership. On the other hand if the creator, owner and client is just one single class or function, the use of a singleton is definitely an overkill!

Consequently, this particular singleton usage is virtually minimizing the advantages of the pattern, while maximizing its drawbacks at the same time!

Basic reading

Further reading

No comments:

Post a Comment