Unit Testing as Documentation

Unit Testing as Documentation

Comments and documentation often lie. The only truth is the code.

Steve Watts commenting on Chris Stryker’s Clean Code presentation at NIWeek 2019

Now I don’t think Steve is accusing the developer who wrote the code or documentation of deliberately lying, but we’ve probably all encountered code where the comments do not match what the code is doing. Often the code gets changed and the comments don’t get updated. Sometimes the comments are aspirational and describe what we intended to do (but never actually got around to). Regardless of the cause, there is often a mismatch and in this mismatch, the only arbiter that actually matters is the code itself.

Code always tells the truth. When it is run, specific inputs produce a specific output regardless of what the comments or documentation says. What if we had defined for each set of inputs, what specific outputs we are expecting? That’s a good start, but how do we know that is what actually happens? Well, let’s put that in some code that is runnable. That sounds an awful lot like a Unit Test.

Just by looking at this test one can tell that if 2 parameters have the same value, and the names have different cases, Verify should still output a true value (ie. Verify is case insensitive as far as the names are concerned). At least that is the intent. However unlike a comment, if want to make sure, we can simply run the test.

Don’t waste your time writing comments that go stale. Write Unit Tests instead. You will be forced to update them as your code changes. They also allow you to verify that what you intend to happen actually happens simply by running the test. You’ll always know exactly what your code does. As an added bonus they will also help you detect bugs before your customers do!