3

I have read a number of discussions on web and stack which claim singletons to be evil. Like: root-cause-of-singletons and Why is Singleton considered an anti-pattern?

I read comments like "singletons make code complex, pain to reuse and test". I work with code that has Spring Services which are stateless singletons and I can't see how those points hold here.

Do such services also qualify as bad practices and why? Or all the debate is on statefull singletons only?

Community
  • 1
  • 1
tunetopj
  • 561
  • 2
  • 5
  • 15
  • 1
    The evilness is only with stateful singletons – ControlAltDel Nov 03 '14 at 17:59
  • @ControlAltDel I don't understand why this question is "primarily opinion based". As Marko answered, it is clear that the debate I pointed to was on singleton pattern and was not related to Spring's singletons. – tunetopj Nov 04 '14 at 19:00

3 Answers3

4

You have confused Spring's singletons (a universally good thing) with the Singleton design pattern, which suffers from the issues talked about in your referenced material.

The Singleton pattern assumes the existence of a static global variable referring to the singleton object. It often also assumes a lot of boilerplate code used to manage the singleton's lifecycle (lazily initialize it, for example).

Spring neither makes you implement the Singleton pattern, nor does it use it internally. Spring singletons are created declaratively and wired together into complete object graphs, including the resolution of circular dependencies.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

(Comment as answer for readability.)

Singletons aren't intrinsically evil, they're just easy to mis-use.

If you're not managing the singleton-ness of the object there's even less of an issue.

I'll disagree with the others regarding singletons with state; while it can be done wrong, there are many singleton patterns with state that work just fine, e.g., a pool.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
2

A Spring Singleton is evil if it is stateful. A stateless singleton is fine :

  • no field,
  • or stateless fields (for example a datasource), initialized at startup.
Alexis Hassler
  • 752
  • 5
  • 16