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. Continue reading “A Valid Use-Case For Singletons”