Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection: What's wrong with good old-fashioned refactoring?

DI creates an extra layer of abstraction so that if your implementation class ever changes you can simply plug in a different class with the same interface.

But why not simply refactor when you want to use a different implementation class? Other languages like Python and Ruby work fine this way. Why not Java?

like image 219
Chuck Avatar asked Dec 13 '22 23:12

Chuck


1 Answers

That is an incorrect characterization of dependency injection. It is not that you have one implementation of a particular interface that changes over time; rather, it is possible that there will be many different implementations of an interface all at once, and which implementation will be used can vary over multiple different runs of the program. For example, in your actual program, you might want to use one implementation, while during unit testing, you might want to "mock out" that implementation with an alternative version that is easier to test. In this case, refactoring is not a solution, because you need to be able to test all the time without interrupting the rest of the development process.

It should also be noted that dependency injection is usually used as a solution to the Singleton anti-pattern; it allows one to have a singleton object that can be easily mocked out during testing. And, if later it turns out that the singleton assumption really is incorrect, that singleton can be replaced with various implementations.

Some resources which you may find helpful in better understanding the topic:

  • Java on Guice: Dependency Injection the Java Way
  • Big Modular Java with Google Guice
  • Singletons are Pathological Liars
  • Why Singletons are Evil
  • Root Cause of Singletons
  • Dependency Injection Myth: Reference Passing
like image 105
Michael Aaron Safyan Avatar answered Jan 23 '23 05:01

Michael Aaron Safyan