GetNoticed IT#8: Singleton

Hello there!
The infamous singleton – a pattern and an anti-pattern. Despite it’s bad reputation I decided to use it in my project for GetNoticed contest. I explained it why in one of my posts: my singletons consist of methods only and they’re sealed.

Thread safety
The most dubious concern in singletons is their thread safety. This can be fixed by using locks (examples here) or by including private and static constructors. Private constructor makes it impossible to create an instance of a singleton class anywhere in the code. Static constructor will be executed only once: when first instance of the class is created or when a static member of a class is referenced.

Whenever I need (and so far I have used them only once) a singleton I follow fourth template proposed by C# in depth. The template consist of private and static constructors, private static readonly instance field and public static property that gets instance.

Most sources I have encountered so far point out 4 main reasons to consider it as an anti-pattern.

  • accessible as a global instance and thus hiding dependencies
  • violation of SRP: singleton class is responsible for its business purpose and for its life cycle
  • tight coupling and weaker testability due to use of concrete singleton implementation
  • singleton carries its state as long as the program runs

These disadvantages are properly described (and discussed) by Scott Densmore and Johannes Rudolph. I recommend to read their posts.

To conclude I would say that I will be extremely careful next time I think about using singletons and will probably think of other solution for more complicated things than simple implementations of IComparer<T>.

Thanks, Michal