CodeSOD: Single or Mingle

This post was originally published on this site

The Daily WTF

Singletons is arguably the easiest to understand design pattern, and thus, one of the most frequently implemented design patterns, even- especially– when it isn’t necessary. Its simplicity is its weakness.

Bartłomiej inherited some code which implemented this pattern many, many times. None of them worked quite correctly, and all of them tried to create a singleton a different way.

For example, this one:

public class SystemMemorySettings { private static SystemMemorySettings _instance; public SystemMemorySettings() { if (_instance == null) { _instance = this; } } public static SystemMemorySettings GetInstance() { return _instance; } public void DoSomething() { … // (this must only be done for singleton instance – not for working copy) if (this != _instance) { return; } … } }

The only thing they got correct was the static method which returns an instance, but everything else is wrong. They construct the instance in the constructor, meaning this

To read the full article click on the 'post' link at the top.