Re: Singleton Considered Harmful?
Posted: Aug 27, 2007 3:55 PM
> > One of the problems with the Singleton is that it is
> > heavily overused. I have just started on a project
> > is struggling in its final phases. The entire code
> > is littered with Singletons making it difficult to
> > introduce badly needed unit tests as the Singletons
> > introduced a hard wiring of dependencies between
> This is one of the biggest problems with the Singleton
> pattern. Even though it's so often used, it's generally
> Properly implemented, the Singleton pattern should not
> 'hardwire' classes together. The most overlooked part of
> the Singleton pattern is that the GoF description includes
> the ability to subclass the Singleton. For example, in
> your testing example, Singletons, when configurable, can
> actually be a easy place to insert mocks and stubs for
> dependencies of a class. The way most Singletons are
> implemented does not allow for that.
True, singletons can be written to be configurable, which does facilitate testing, but they're still "hidden" dependencies. By that I mean that the dependency is an implementation detail, which is retrieved by the class itself.
> The main reason I see for the lack of Singletons that can
> be subclassed in Java is that far too much emphasis is
> given to the 'uniqueness' of the singleton. If you want
> to protect the Singleton from multiple instances you need
> a private constructor. I've never really run into a
> situation where a truly single Singleton was really
> required and as you point out, this isn't possible in Java
> for the general case.
Yes. I think Singleton is the wrong way to implement uniqueness.
> The real problem is the overuse of global objects and
> people only half-understanding what they have read.
Agreed. A Singleton typically is a global variable, though.
> I think it's good for when you want a shared object. A
> classic example is a local cache. A lot of people say
> that DI makes Singleton unnecessary and they may be right
> but DI containers seem to be the current one-size-fits-all
> solution. I'm not convinced it will never fall out of
> favor. If this isn't correct and DI containers are the
> ultimate future of programming, then we should be looking
> at pulling it out of XML and formalizing it as a general
> purpose programming language.
I'm not a big fan of DI using external XML. Instead, I prefer to pass in the required collaborators as constructor parameters to each class, using factory functions where necessary. This puts the key information about which classes are actually used in the application in the code itself --- at the top level, the "main" function.
If you do this, then singletons do become unnecessary --- if you need only one instance, you only create one, and pass it around. Also, this greatly facilitates testing, as you can freely pass in subclasses or alternative implementations of the interface as necessary.