I've been reading up on dependency injection and I understand the appeal of specifying dependencies in XML, as is done in many frameworks. I work on a large system where we normally call factories to get concrete objects, and am struggling to understand why manually injected dependencies as shown in this Wikipedia article are supposedly any better.
It seems to me that calling a factory is better because:
It seems to me that dependency injection only offers benefit when the calling code has to decide on the concrete class for the dependency. Almost like "Here's my data, now process it."
Is there something I missed?
Update: To clarify, our existing code mostly calls the factory directly. So to get a new Ball object, you'd see code like this:
Ball myBall = BallFactory.getObject();
A lot of those factories are implemented to allow run-time registration of new concrete object types - a plugin framework.
So after looking at some of the initial comments it seems like with DI my calling code would not normally pass in the Ball object, but instead the BallFactory. I guess the benefit of that is that the class may be more generic, since it doesn't even have coupling to the factory it uses.
Dependency injection helps when unit testing. It allows you to separate and isolate the functionality of your class, because any of it's dependencies can be injected (and therefore also mocked) into the class. This is particularly useful if the dependencies access external resources, such as DBs.
I read an article recently that demonstrated the advantages of dependency injection in testing. It's specifically about static methods but the same could apply with factories.
http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/
Like @deceze says though, if you inject your factories you get the best of both worlds...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With