Nothing is too trivial to test

by Charles Miller on October 1, 2008

It was really trivial code. A wrapper around a HashMap (dictionary) to temporarily cache some values that were getting too expensive to calculate every time. While writing it, I pretty much convinced myself that this code was so simple there was really no point writing unit tests, but as I got close to checking the code in I realised that the first thing my code-reviewer would ask was “where’s the test?”

So I wrote a test. And it failed. It failed because I'd made a really dumb typo in the constructor of one of the nested classes I was using as cache keys, writing this.username = (user == null) ? null : username instead of this.username = (user == null) ? null : user.getName(). This simple mistake meant my cache would be at best useless, and far more often entirely inaccurate.

Lessons for the day, there are two:

  1. Nothing is too trivial to test
  2. Even the mere threat of a code-review leads to better code

Previously: Everything that is wrong with Facebook apps in one screenshot

Next: …and all places are alike to me