tags:

views:

339

answers:

6

Duplicate:

What is so bad about Singletons?

I was reading this question, and was surprised to see that (s)he considered a singleton to be considered a "bad practice," and in fact thought that this was common knowledge.

I've used singletons quite a bit in any project that uses iBatis to load the queries from XML. It great improves speed in these instances. I'm not sure why you wouldn't use them in a case like this.

So... why are they bad?

A: 

Duplicate of this question:

Andrew Grant
+1  A: 

They are not necessarily bad, just misused and overused. People seem inexplicably attracted to the pattern and look for new and creative ways to shoehorn it into their application whether or not it really is applicable.

Andrew Hare
A: 

Singletons are not bad practice at all. In fact they are extremely useful for many situations. But they do have two major areas ripe for abuse and/or failure:

  • Unit testability
  • Multi-threading

Both can be handled, but beginners often neglect to do so (usually through ignorance) and it ends up causing far more trouble than they know how to deal with.

Rex M
+1  A: 
Joel Coehoorn
A: 

They arent necessarily bad, its that they tend to be overused, and used a lot when they arent needed.

People who use singletons tend to put EVERYTHING in singletons (like a recently fired coworker of mine) who had a rather large desktop app with all possible data stored in static global instances. Lets just say it caused some memory issues, among a host of other problems.

Neil N
A: 

They are usually considered bad in conjunction with unit testing.

If you have a singleton, that means one or more of your classes are using it somewhere in some methods. That's a dependency you cannot spoof when unit-testing your class because the class is directly using it without requesting it through either its constructor or through a property.

That is usually why people say they are "bad".

Also, in a multi-threaded app, lots of people implement them badly enough that there is a chance for the instanciation to be called more than once.

Denis Troller
That's not the only reason they're bad for multi-threading. Done wrong they can become a bottleneck that forces serialized access to a resource that could otherwise be used in parallel.
Joel Coehoorn
True, thanks for correcting me.
Denis Troller