0

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?

Community
  • 1
  • 1
Matt Grande
  • 11,964
  • 6
  • 62
  • 89

5 Answers5

3

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
  • 344,730
  • 71
  • 640
  • 635
3

They're a tool, and like any tool there are times you should use them and times you should use something else. In this case, it's very often true that something else (Factory, static class) would be better in situations that at first glance may seem appropriate for a Singleton.

When Design Patterns came out it seemed like everyone jumped on the Singleton bandwagon — they were everywhere, even places they shouldn't be. What you see now is a (perhaps well-deserved) backlash. Not that you shouldn't use them at all, but it might be a good idea to take a step back and look at all the options available.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
2

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
  • 142,167
  • 33
  • 283
  • 313
0

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

Neil N
  • 24,862
  • 16
  • 85
  • 145
0

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
  • 7,411
  • 1
  • 23
  • 36
  • 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 Mar 24 '09 at 19:00