Why Test?
The fact of the matter is, we could spend all of our time writing tests, and never get any production code done. The only way to know how much to test is by knowing why it has value, because then it is possible to do it enough to get the benefits without overdoing it. Of course, often the opposite is the case, where we choose not to test at all, and this, too, can be remedied by understanding the value of having tests.
Here are a few ideas on what value testing brings:
- Documentation - the tests can serve as the documentation for the code, removing the need for a lot of inline documentation. The advantage to having the tests be the documentation is that unlike inline documentation, these documents actually run, and are always guaranteed to be up to date, assuming they run successfully. The documentation is guaranteed to be practical, as well, since it makes real use of the code it is documenting.
- Ability to change - If a system is sufficiently small, one can be fairly certain that a change will not affect another part of the system. However, once it grows to any size, it becomes very uncertain whether a change over here will have negative affects over there. If there are tests for the code, changes can be made without any concern for the effects of the changes, because the tests will catch anything that is broken. It is definitely very freeing when one can change things without fear.
- Clearer code - This is hard to quantify, but I know that writing tests affects my code, and affects it for the better. The code is less tightly coupled, and has hooks in it so that others can test it easily as well. It is better thought out, and easier for other to understand. I would encourage anyone to try test-first design, and see for themselves what it does to their code.
- Blank screen syndrome - Dave Thomas mentioned the fact that the tests always give one a place to go first, and a clear way to start developing. I've often stared at a blank screen with something that I wanted to do but not a clue as to how to start. The tests help me out of this, by being a fixed point to anchor the rest of my code to.
- Probably there are others that you yourself can think of...
So the goal is to test to the degree that gives us the most of each of the benefits above without losing the obvious value of delivering software. How to balance this becomes clearer if we focus on test a little, code a little, in constant cycles. This cadence helps us to know when we've strayed to far from having tests or implementing code.
Let me make my first assertion...
Copyright (c) 2001 by Nathaniel Talbott. All Rights Reserved.