Jan Hoppmann wrote:Wrong. Singletons are extremely good practice if you know how to use them.
In one of my applications, I use a singleton to store the application's settings - why should I have many copies or read them every single time a user loggs on, if I can just store them in a singleton?
Singletons are used whenever you need one, and exactly one, object of something.
I disagree. Singletons are almost always not good practice. One of the problems with singletons are that they make your code hard to
test. Singletons, implemented with the classic static instance pattern, are hard to replace by mock or stub implementations, which is what you very often want to do in unit tests. You can use a dependency injection framework to get around this (when testing, you let the framework inject mocks instead of the "real" objects).
You can find a lot of discussion about why many people regard singletons as bad by searching for "why singletons are bad" or similar search terms.
Especially singletons which have (mutable) state (member variables) are bad, because those variables are essentially global variables, which can cause all sorts of issues, for example with
thread safety.