Authors deserve more credit than they get. Coming up with a simple example to illustrate a principle is harder than it looks. Good authors have to do this all the time. They provide the examples that become anecdotal when describing the concept to a friend or colleague, and most of us, myself included, never take the time to think about the process.
That was until today when I needed an example of Dependency Inversion to help explain the concept to a classmate. I must have thought up 10 or so bad examples before I finally came up with one that I felt was sufficient for doing the concept justice: Piping on a cake.
Here’s my explanation:
Say you are going to ice a cake and you want a very specific design for the piping as well as your favorite flavor. If you go to the store and buy a premade disposable piping kit that already has the design attached and the icing in the tube chances are you'll have to compromise and choose a kit that doesn't quite fit your needs.
If you decide to get your own piping kit that comes with interchangeable nozzles and no icing, then you can pick up your favorite icing as well and get exactly what you want. This is how dependency inversion works.
In a VB.NET program, the first scenario would be like this:
Dim piper As New PremadeStarShapedBlueRaspberryIcingPiper()
This is simple and straightforward, but not reusable. If you wanted strawberry or some other icing, you need an entirely new class! This means code duplication to accomplish the same tasks, which leads to bugs.
For DI, we would do this:
Dim piper As New Piper(starShapedNozzle, BlueRaspberryIcing)
This is a little more work up front, but if you think about it this work is happening in the background in the first example. In the first example the piper knows more than it needs to know about the nozzle and the contents, which makes it less reusable. This time, if I wanted Strawberry Icing I could just pass it to the piper and the piper knows that the ingredient is pipeable and that's all it cares about.
What do you guys think? Is there a better example you’ve used? Does my example suck? I’d love to hear your thoughts.