1

Many articles in Internet say that singleton is an anti-pattern, because it makes debugging more difficult.

However I don't understand why debugging a program with a singleton object is difficult. Please explain.

I think that singletons are inevitable, when we need (usually for performance reasons) lazy initialization of a controller object. Or are there any other alternatives?

-1

Singletons are not always inevitable, you can use the monostate pattern in a lot of cases, however, it has the same issues as singletons, most notably it is to do with governing global state.

For why having global state is bad, take a look at the following stackoverflow post: Why is Global State so Evil?

Personally, I prefer to have a monostate class over a singleton as it allows me to inject this as a dependency rather than referencing the singleton's concrete implementation (via MyClass.Current), at least with a monostate you can abstract away the fact that there is a single instance of data, and allows me to test classes relying on it easier.

  • "A monostate is a "conceptual singleton" - all data members of a monostate are static" from wiki.c2.com/?MonostatePattern that sounds rather nasty as well. Why not use simple IOC where you have full control? – Esben Skov Pedersen Nov 14 '16 at 19:45
  • I didn't want to assume that the OP was using an IOC container. As you suggest, you may register your instance as a singleton if you wish, but in the end you are still left with global state. – Matthew Nov 14 '16 at 20:12
  • We don't need to use a container to use IOC. It is just a pattern. – Esben Skov Pedersen Nov 14 '16 at 20:55
  • @EsbenSkovPedersen, "We don't need to use a container to use IOC". Without a container, it's not IoC; it's just DI. But that's a common problem with IoC/DIP/DI, it's a great way to write code, but everyone seems to have a slightly different idea as to what the terms mean. – David Arno Nov 15 '16 at 6:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.