patkua@work

Singleton vs Single Instance

I’ve been fighting the fight against the Singleton pattern on a new code base and got me thinking about easy it is for developers to equate Singleton with Single Instance and, in my experience, more often than not, all they really want is a Single Instance. Of course, you may have proper uses for the Singleton pattern (all listed in the Gang of Four book I’m sure) yet there are many reasons why you should default to Single Instance.

Singletons often tend to be a pain because their “singleness” often makes testing a pain, with shared state persistent across different tests, and additional code to “reset” it. Worse still is the way that their global state makes them just a little bit too easy to stick into the middle of a block of code, without regard of whether or not it belongs. It often takes a while to unwind any dependencies and identify appropriate responsibilities. It’s global nature also often makes it all too tempting for it to evolve into a bit of the god object.

Exit mobile version