1

All the services in Angular are singletons. Singletons are known to be bad practice.

I know that many people (Including me) are very happy with Angular. What am I missing here?

gilamran
  • 5,914
  • 4
  • 27
  • 48

1 Answers1

3

Singleton is a super useful pattern. It's hard to imagine building software without it! Imagine, for example, constantly recreating an object that hashes a million records.

The problems lie in the implementation:

What is so bad about singletons?

They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code,instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.

The bulk of the criticism would seem to be pointed at a very old-fashioned implementation of the singleton pattern, where they are available globally:

public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   protected ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}

Using a dependency injection container (like angular or spring) overcomes most of the above objections. The container handles life-cycle and injecting the singleton instance into client code. You can always replace the injected singleton with a different one for testing purposes.

In short, using a DI container makes it easy to use singletons without the potential bad effects.

Robert Moskal
  • 19,576
  • 6
  • 57
  • 76