4
Yeah69
8y

I propagate to others that the use of singletons is bad, but still use them on rare occasions in code, which only I touch. 😈🐒

Comments
  • 0
    Why are singletons bad?

    I love the bastards.
  • 0
    Just read up on this, top answer on SO is that they are bad because they:

    Are concrete, violate single responsibility, cause tightly coupled code, carry around state for the duration of the application.

    Umm... No, no, no (at least not in my applications), and best get rid of any kind of persistence / caching then.

    Any other reasons? (genuinely interested)
  • 1
    @chrizzle You have to be catious with Singletons. One big argument is that they decrease the testability or they make unit tests inconvinient.

    For instance, it gets difficult if the Singleton has fields, which alter the behaviour of the methods of the Singleton. Unit tests runner usually do not have a set testing order for the unit tests. So each single unit test cannot make assumptions of the Singleton being set up right. Thus, the developers need to setup the Singleton in each single unit test's arrange phase. If he forgets to, then the test results may be random (possible false negatives).
    It is easy to forget that a class is calling a singleton.

    An alternative to singletons is to dependency injection. In the test scenario from above you would have to inject an instance of a class, which has the same behavior as the singleton through the constructor. Thus, the developer is forced to instantiate a concrete instance. So he won't forget to set it up right. Or even better, he can mock
  • 1
    @chrizzle the dependency.

    That said. There are use cases, when singletons are acceptable. Mostly, when they conceptionally work like a sink. Thus, it only gets input, but gives no output. This means, that the singleton has no influence on your program.
    For example, logging frameworks often use singletons. But logging does have no influence on the classes which use it.

    Thus, singletons should only used with caution and in specific use cases. So they are widely controversial.

    In an interview of the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides) about their famous book "Design Patterns" 15 years after they were asked how they would "refactor" the book. Erich Gamma told: "When discussing which patterns to drop, we found that we still love them all. (Not really—I'm in favor of dropping Singleton. Its use is almost always a design smell.)"
Add Comment