Why I Document Existing Code With Tests
25 February, 2014I have written my share of code without a single test, this has surely left the next guy weeping in my wake. But I have lived and learned, and now have the civility to leave behind a substantial test suite. Likewise, when I find myself being the next guy, I try not to make a change without first writing the test code.
Before the Fix, Document With a Test
It is a simple rule, apply TDD to the existing code. With an existing code base with little documentation and possibly vague direction, I like to identify the smallest unit test that documents the existing behavior. At a minimum it allows me to move forward with an implementation that is coupled with proof of correctness. In challenging situations it uncovers the ambiguities and ultimately leads me to the right questions. If I do (rarely) determine that some code is unreasonable to wrap in a unit test, then I usually have enough information to make a good case for a refactor, and the domain knowledge to ship a solution under test or not.
Intended and Unintended Benefit
I have found this approach to be incredibly useful. With it, I have uncovered bugs that would likely not have been found for some time. In that case, having the failing tests provided the basis to plan and fix the long hidden bug along with the original feature that brought me there in the first place. There are certain cases where I have skipped it, and in trivial code changes that may be fine. However, it has saved me from myself enough times to be the go to approach. As with all test-first techniques, the benefits are worth the effort.