views:

163

answers:

2

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?

+12  A: 

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:

Michael Aaron Safyan
Also: A class that needs a dependency does not need to worry about to construct that dependency. That can be left up to the writer of the implementation.
Jeremy
Good explanation. Thanks.
Chuck
Thanks for the resources. I wish I can up-vote twice!
Enno Shioji
@Zwei: here, let me help you with that [+1]. But no, really - a very good overview, thank you Michael.
MicE
A: 

So you are saying Python and Ruby can't have dependency injection? Or Java can't work fine without DI?

Besides you've missed the one of the most characteristic of DI, that you can have Dynamic DI, not just at compile time, but at run time. In Software Engineering there is always a question of is there too much Abstraction and too little and it really comes down to how you design a solution to your problem

hhafez
hhafez
DI is a pattern not a framework, in any case, here is a framework that performs DI for python: http://code.google.com/p/snake-guice/
gpampara