I understand dependency injection, but have not had that “ah” moment, where it clicks and I really see the light.
Why should I use DI? Also, when mocking objects like those which use the file system, what would the mock object be capable of? Does it just do dummy calls (so does not really use the file system)?
Let me go a couple steps farther from hvgotcodes answer:
is your original class with the hard-coded dependency.
is your newfangled class with the injected dependency.
So far, so good. Now, let’s take
Collaboratorand extract an interface from it; call itICollaborator. Now your newerfangled class looks like such:What does this buy you? Well, you can, in your code, create this class to behave like the first example as such:
Pretty cut and dry easy. The beauty comes from when you want to use a different type of
Collaborator— perhaps even a mock or fake. So long as it implements theICollaboratorinterface, you’re golden:Voila! You now have a unit-testable
Serviceinstance that doesn’t drag the concreteCollaboratoralong for the ride (which would be breaking true “unit” testing).