A Valid Use-Case For Singletons

Single-instance classes can be a useful tool, in object-oriented programming.  Generally, singleton classes are discouraged and categorized as a likely code smell, because they too closely resemble global variables.  They can lead to tightly-coupled code and hidden dependencies, which makes unit testing difficult.

That remains good advice; if you can avoid using singletons, do so.

There are, however, valid reasons to use a singleton.  Ironically, they are especially useful for unit testing projects which need to interact with ‘statically-oriented’ legacy code libraries – libraries which don’t contain objects or classes, and therefore can’t be easily mocked in unit tests.  In these cases, a singleton class can help ‘wrap’ the static functions into an object-oriented interface, making your application code easier to test.  This post describes the general strategy used for this approach.

  1. Create an abstract interface, with methods that resemble your legacy library’s needed functions.

  2. Create a singleton class which implements that interface, calling the legacy functions in the underlying implementation.
  3. In your application; wherever your legacy functions are needed, store a reference to the previously-defined abstract interface.  In production code, you can assign this to your singleton ‘legacy-wrapper’ class; during testing, you can assign a fake stub, instead.

    Note: this is pseudo C# code; in C++, you would use a reference or a pointer to the abstract base class.

Here is the differentiator.  Here is the reason why this singleton is “okay,” while other singletons are “bad”; our application never interacts directly with the singleton class.  We handle all interaction through our ‘proxy interface.’  The only purpose of the singleton in this scenario is to protect the static state of our legacy library, to ‘wrap’ it into an object-oriented interface.

Leave a Reply

Your email address will not be published. Required fields are marked *