TDD with the Dependency Inversion Principle
In terms of making a class more testable, the DIP is probably the most important principle on the list for me. The DIP suggests that details should depend on abstractions. To me, this means that the specifics of a program that does not really belong to a class should be abstracted. The DIP allows us as developers to remove a concrete implementation of a routine or program and put it in a different object altogether. We can then use the DIP to inject the object that we need, whenever we need it. We can inject the object that we need in the constructor, passed as an argument upon class instantiation, or simply expose a mutator function.
Let’s revisit the ToyCarValidator
class that we created earlier in this chapter to see how we can implement the DIP.
How will this look in our code?
Going back to the ToyCarValidator.php
class, you will notice that in the __constructor
method, we have instantiated two classes: