Programming to Interface

Coding to interfaces is a technique to write classes based on an interface; interface that defines what the behavior of the object should be. It involves creating an interface first, defining its methods and then creating the actual class with the implementation. At first, it looks like over coding, but, there are two main reasons that why I decided to go for it: Test Driven Development and Flexibility.

On the testing side, is absolutely needed. TDD is about creating the tests for the functionality to achieve, to later develop the code required to pass the tests. As there is no implementation of the code yet, using Interfaces to Mock objects is necessary to accomplish the test cases; when the actual implementation is ready, is just a matter of substituting the mocks and injecting the real object. If the object complies with the interface, your tests will behave the same way as the mocks. It also works when creating tests that depend on code done by another person or team and you do not have the real object yet.

On the other hand, there is flexibility and maintainability.

To put it simply, instead of writing your classes in a way that says

I depend on this specific class to do my work

you write it in a way that says

I depend on any class that does this stuff to do my work.