Dependency Injection: a discussion of the pros and cons

Hey Tony, I hate to be the bearer of bad news, but so far no one has used the word “crap” to define your code except you (and @s_molinari when he wrote “Holy Crap!” … but I don’t think that was directed at your code either…)

We understand that you’ve been “bullied” over your code at other places. We are not trying to do that here. We are simply trying to get a better understanding of when a singleton is better than DI. Or really more importantly, the downsides to DI versus its advantages.

Yes, we’ve pasted a few segments of your code, but not to review it, but rather to see if we can interpret why the design decisions were made. Again, consider this a learning experience. A lot of us like to look at what others have done to see what we can gleam from their work in comparison to the practices and works that we have created. It is one of the many ways we enhance our abilities, as someone may have done something we never considered before.

So with that said, @TomB showed a way for your existing logic to handle at least 1 dependency without the use of a singleton pattern. So let’s conceptually talk about the merits of that example.

Does it make sense?
To me it does.

Does it solve the a problem on providing a dependency to an underlying class?
Yes, it does.

What does a singleton provide that the DI implementation doesn’t?
A single instance of the dependency.

Is there a reason why you might not want that?
Yes.

What if you need to ensure all existing properties of the singleton are sufficiently overwritten when a new class needs to use that dependency?
Singletons make that more cumbersome as you’d have to manually overwrite each property, if you add a property, you may have to go and do that in multiple places. Using DI you can be guaranteed a new instance that doesn’t have any remnants of a prior usage hanging around.

If that isn’t a problem, then a singleton still fits the bill (and that very well may be your case, I don’t know, and I really don’t care… as it isn’t about your specific use case, but the concept as a whole that we want to discuss).

1 Like