Abstracting away Windows COM dependencies

The Windows Component Object Model (COM) system is a massive, massive dependency.  How big and complex is it?  Well, I usually list it on my resume as a separate line item.

When you first decide to incorporate COM-aware code into your application, you’re signing up to import an entire ecosystem of macros, interfaces, types, headers, class-specific smart pointers… and headaches.  Naturally, it makes sense to try and segregate that mess from the rest of your pristine code.  Encapsulate it in the smallest container possible.  In general – when I require functionality from a COM type – I immediately abstract it away, behind a more user-friendly, ‘standard’ C++ helper class or interface.

If you do it right, consumers of your code never need to know it’s utilizing COM at all. Continue reading “Abstracting away Windows COM dependencies”

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”