Step 73: Resist the Temptation of the Singleton Pattern~ Sam Saariste

This is the 73rd step towards gaining the Programming Enlightenment series. If you didn’t learn the 72nd Step, read it.

Pic: Source

What is Singleton Pattern?

Singleton Pattern is one of the software design pattern mentioned in the Gang Of Four’s design patterns book.

This design pattern describes restricting the instantiation of a class to one “Single” instance.

Why use Singleton Pattern?

Singleton Pattern is useful when exactly one object is needed to be used as a global instance to coordinate across the system.

Why Singleton is anti-pattern?

  1. The singleton classes do not allow for test-driven development. Since, we don’t have control over creation, it makes it harder to test. Without dependency injection we cannot use mock objects in our tests.

Why resist the temptation of the Singleton Pattern?

Experience shows that most singletons really do more harm than good. It makes life of developer easier on the short term, but hinders testability and harms maintainability.

  • Singletons cause implicit dependencies between conceptually independent units of code preventing mock implementation.
  • Singleton with mutable state introduces tests being dependent on another.
  • With multi-threading singleton pattern; would have to be implemented as double-checked locking pattern (DCLP). Even DCLP isn’t thread-safe in many languages.

TL;DR Restrict the use of Singleton pattern to the classes that truly must never be instantiated more than once. Don’t use singleton’s global access point from arbitrary code instead use an interface to provide it.

--

--

MyView androidView;

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store