Monday, August 6, 2012

Understanding Dependency Injection

Based on all the articles and postings I've found via Googling the subject it's my guess that getting a handle on what Dependency Injection can be difficult for some people. For others, not so much. So, I'm going to post some of the resources I've found and add some comments to extend what they have posted to if I feel the need.

Basic Explanations

One of the more basic descriptions I've found is this one in a blog post by Kevin William Pang titled Dependency Injection For Dummies. What I liked about it was how it used simple images to assist in developing mental pictures for the concepts. I do think it came up short in one aspect though. In the "...Why Should I Care?" section he did cover how DI can be used for testing but he didn't provide an image or tie that back to the analogy. I believe it's one of the most useful aspects of DI and worthy of a bit more in-depth explanation.

So here:

How do you test that you can use a car, the dependency in this analogy, to go to the store? You inject a mocked instance of a vehicle. You can think of it as something like a driving simulator.
Totally stolen and then modified graphic
Note the purple, virtual vehicle.
This totally removes the need for a vehicle of any kind to verify that you know how to make a trip to the store via an appropriately configured vehicle.

To add to that, you can inject a mocked instance of the store, the shopping list and the money it will cost you to make the purchase. Then, at the end of this virtual trip to the store, you can test that you came back with all the items on your list.

To stay with the analogy, to do further testing, you can inject a store that doesn't carry 2% milk and then verify that it either returns with no milk or that skim milk is substituted depending on the business logic that is expected to be implemented. You can also substitute a virtual vehicle that shouldn't work, like a riding lawn mower, and check the error response. Alternatively, inject an obscure vehicle, such as a street licensed golf cart, and ensure that it can make the trip to a neighborhood store but fails if there is a highway where the golf cart isn't allowed on the route.

In the comments section, brian goes a little way into making modifications for the classes. As my thinking is along the lines of testing scenarios I'd like to carry that a couple of steps and make it so the Car class would implement alternate modes of transportation as mentioned above and then to add an age attribute to the Person Class and then verify that the target vehicle will ensure there is a place for a child seat for passengers under a given age.

No comments:

Post a Comment