Testing and Design are often at opposite ends of the software development life-cycle. However, test-driven development is an excellent way to drive our design. It can help us build better classes and improve re-use. This episode focuses on TDD and how it can point us to full-featured classes with better error handling and messages.
Test-Driven Development For DesignWe previously looked at unit testing and class-level quality assurance. While those are important tasks once we get the class implemented, they are better incorporated into the design process. When we do, it ties our testing (validation) more directly to requirements. Thus, we have goals for each bit of code to achieve. We drive our implementation by the tests we need to pass. This approach is not the only way to do so. However, it does translate requirements to the implementation. It also can help us find gaps.
Testing ResponsesTesting centers around the responses and behaviors of our classes and methods. Thus, our class must support a message, exception, or value that the test is looking for. In the case of exceptions, I find testing a key indicator of where we need to support them or report errors. That is because a unit test has this basic format.
Make a call. Gather results. Compare results to a set of assumptions.That third step will highlight areas where we have the proper amount of error handling and messages supported.
A Simple ExampleLet's consider a simple example to show how this works. In our example, we have a method that takes two numbers, adds them, and returns the sum. The requirements tell us we need to verify the sum is correct; we warn the user if a negative value is sent. Finally, we need to warn the user if they do not provide a number. If we implement first and then test, we can easily forget the latter requirements. We will probably add the numbers and return the sum. It is not until we get to testing that we will realize we have some exceptions handle. If we take the test-driven development approach, then handling these exceptions and related messages will be in our minds from the start. That can heavily influence the kinds of things we want to support and return as we design our class.