Lots of people having numerous bog entries, books, and essays, etc. on mock objects and testing.
Here is my attempt to express a simple but critical concept with development. I plan on breaking it down to simple examples.
I will provide smaller more focused blog entries just like I focus on coding smaller more focused classes, methods, and tests. 😀
The purpose of creating interfaces and utilizing mock objects is to eliminate dependencies.
The goal is to have loose coupling between objects that interact.
What does coupling mean?
To summarize wikipedia, coupling is the degree to which an object relies on another object.
If an object relies heavily on another object, then it is said to be tightly coupled.
ClassA is said to be tightly coupled to ClassB because the Calculate method accepts the concrete class ClassB.
ClassC is said to be loosely coupled because instead of using a concrete class as a parameter, the Calculate method accepts an IDoStuff interface. Now ClassC isn’t coupled to any specific implementation of IDoStuff.
Here is an example of the flexibility this provides :
The quick summation is that since ClassA’s Calculate method required ClassB, ClassA was tightly coupled to ClassB.
With ClassC we leveraged the IDoStuff interface to de-couple ClassC from any implementers of IDoStuff. So ClassB and ClassD can implement IDoStuff and ClassC is not coupled to either of those implementations or any implementation. ClassC is only coupled to the interface.
Designing your code to be loosely coupled pays huge dividends for testing.
So that’s the brief focused blog entry for part 1!