TDD and throw-away code

If I had started with test-first approach, I would have saved half a day or so.

I frequently hear people say that it doesn’t make sense to write unit tests for POCs, or single-use or throw-away code.

And I’m not here to tell you whether you should or should not write unit tests for such code. But I recently wrote some code, and I had an interesting experience.

I wanted to gather some statistics about some popular code bases, so I needed a tool to do some AST walking. I started yesterday morning hacking away at a short script. Not more than 100 lines of code or so. I didn’t write tests. Although I did test frequently, by running the program against itself (it’s a tool to analyze source code, so why not have it analyze itself?)

I did at least create a git repo, because I planned to share a link to the tool along with the results I was planning to report. So I made a couple initial commits, then started hacking away.

Pretty soon I had a version that appeared to be working, so it was time to start adding some “nice to have” features.

First up: Skip analyzing of generated source files. The easy way to do this was to just search the first kb or so of each source file for a string such as “DO NOT EDIT”.

Then I made it read a list of filenames from STDIN.

Then I started adding another feature when suddenly I realized that code was broken. I had been accidentally testing an old version, rather than the current version, and the current version wasn’t working.

So I started backing out changes one by one until it started working again. I eventually discovered that the breaking change was to search for “DO NOT EDIT”. This matched my own source code, obviously. So aborted the analysis.

At this point I commited a working version, then proceeded to re-add the features I had just removed.

A while later I had a working version, with some new features. Then I found a bug.

Then I spent an hour or two debugging, but got nowhere. I took a break.

I came back a few hours later, and decided to start agian.

This time I wrote tests first.

This time I had a working version, with all the same features, in about half the time. If I had started with test-first approach, I would have saved half a day or so.

Of course now I had tests, too. That means it will be easy to add new features or make other changes without fear of breaking things. Of course that will never happen. Because it’s a throw-away piece of code.

Share this