3

Possible Duplicate:
What is so bad about singletons?

I've read in several answers to Stack Overflow questions that using singletons is discouraged and evil. Why is that?

Community
  • 1
  • 1
Joaquín L. Robles
  • 5,552
  • 8
  • 57
  • 86

4 Answers4

6

How many times a class is instantiated shouldn't be dictated by the class itself, but from an infrastructure that provides the single instance. Singleton makes it impossible to leave this decision to the infrastructure. It is a reusability issue, which shows up for instance in the unit tests, but also when the infrastructure tries to provide another instance for a certain purpose.

(E.g. there is only one database connection. But for importing data from another database, it needs another connection. If the database access service would be a singleton, it is impossible to open another connection.)

Stefan Steinegger
  • 60,747
  • 15
  • 122
  • 189
2

Singleton pattern makes unit testing far more difficult, as it introduces global state into an application.

It should also be noted that this pattern reduces the potential for parallelism within a program, because access to the singleton in a multi-threaded context must be serialised, e.g., by locking.

Advocates of dependency injection would regard this as an anti-pattern, mainly due to its use of private and static methods.

Some have suggested ways to break down the singleton pattern using methods such as reflection in languages such as Java or PHP.

vaidas
  • 504
  • 3
  • 9
0

The short answer is they introduce a global-state object in to your code, which breaks your separation of concerns (possibly adding complexity).

Singletons are not without other drawbacks, which you should know about:

http://en.wikipedia.org/wiki/Singleton_pattern#Drawbacks

This article is a bit more verbose:

http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial

vdoogs
  • 573
  • 3
  • 12
0

The reason is probably that they're basically global variables. Even so, they're used quite extensively in some environments. For example, in long running web services. In Java with the Spring Framework for example, the default bean type is a singleton, and typically controllers, services, and DAO objects are singleton (in the sense that the framework only instantiates one instance). They do NOT require locking and are also thread safe, because by convention they contain no state. Typically a request context is passed in, and the controller/service/DAO operates on that.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kevin
  • 23,123
  • 15
  • 92
  • 146