Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is dependency injection better than using factories?

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:

  1. Calling code doesn't need to know or care that a particular dependency exists.
  2. Calling code doesn't need to change if new dependencies are added to the callee.
  3. Calling code doesn't need to have any logic dedicated to choosing the concrete instance to inject.

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.

like image 950
Cobus Kruger Avatar asked Feb 19 '23 11:02

Cobus Kruger


1 Answers

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...

like image 78
Liam Avatar answered Mar 27 '23 06:03

Liam