Singletons: Why Are They “Bad”?

Background The very first thing I want to say is that I don’t think singletons are inherently bad–even if it means I am cast away from the rest of the programming world. There’s a time and a place for the singleton. It’s really common for people to get caught up with their perspective on something that they outright refuse to acknowledge the other side of it. I’d also like to point out that if you have a strong opinion on something and you find that other people also have a strongly opposing opinion on the same thing, there’s probably good take away points from either side. In this post though, I’m going to focus on why singletons are “bad”, because for me it means acknowledging one of the two main perspectives–that they are the best thing since cat videos met…

3 Comments

Dependency Injected Singletons… What?

Background Previously I wrote a bit about singletons. I'm not afraid to say that I think singletons have a time and a place... Okay, I'm afraid to say it, but it's actually how I feel :) After learning more and more about inversion of control design patterns and programming by interfaces, I started to notice just how inflexible singletons are. When you consider using a singleton, you should be considering both the pros and cons without jumping right into it. Here's an example of my approach for mixing singletons, programming by interfaces, and a bit of inversion of control. The Setup I'm actually surprised you got this far. I'm sure you're probably just sticking around to see how messed up this could possibly be. I'm actually proud that this little pattern has worked out so well when I've used it,…

0 Comments

How Do You Structure Your Singletons?

Background I'll skip over the discussion about why many people hate singletons (that's a whole separate can of worms, but worth mentioning) because in the end, it's not going to get rid of them. A singleton is a design pattern that ensures only one instance of the singleton object can ever be constructed. Often, singletons are made to be "globally accessible" in an application (although, I'm still not confident that this is actually part of the definition of a singleton). There are a handful of different ways to implement singletons... so what are they?   The Not-Thread-Safe-Singleton With singletons, the main goal is to ensure that only one instance can be created. Below is a snippet of singleton code that works, but is not guaranteed in a multi-threaded environment: internal class NotThreadSafeSingleton { private static NotThreadSafeSingleton _instance; /// /// Prevents…

0 Comments

End of content

No more pages to load