Is the Singleton design pattern incompatible
with unit testing? I think it is. Singleton assures us that our program will
have only one instance of a particular class and that there will be a global
access point for it. Put those two ideas together,
and what you have is a global variable that can't be replaced. Doesn't sound so bad? Well, try this out: write a set of unit tests which exercise clients of
that variable. If one test modifies
global state, and another uses it, you could have one hell of a debugging chore
when your tests fail. I won’t elaborate
on the pain here. If you’ve ever encountered
it, you know about it.
I think that many of us have known that Singleton is broken for years, but we just haven't stated it out loud. There are always the little exceptions. For instance, singletons cause no trouble at all if we can’t affect state through them, but cases like that don’t come up often. If you have an immutable data structure, it's overkill to make it a singleton. Likewise, if you have something stateless like a factory, well yes, it’s great to have one distinguished instance, but what do you do if you need to mock it? There’s that singleton property, getting in the way again.
Faced with singleton's troubles, many people turn their singletons into fingletons and attempt to protect their instances as best they can.
Yes, there are cases where you might want more protection than this and in those cases you should add whatever protection you feel you need, but let’s face it, on most projects if your teammates can't refrain from calling a static method named setTestingInstance in production code, your project is probably in trouble no matter what you do. On the other hand, if they can, it's easier to keep your software testable, correct and maintainable.