Felix Rambles

Another step to taking back control

Unit testing and code clarity

19 October 2018 — Felix Ple┼čoianu

I don't usually think much about testing. It's just a normal part of programming. Lately, however, I've been playing with a new language, that has unit testing built not just into the standard library (like, say, Python) but the language itself! And the compiler supports code coverage too, for good measure.

It's incredibly fun, writing tests for code you haven't even finished yet, having them pass, and seeing the percent of coverage increasing. And that's a trap.

Because, you see, unit testing isn't your goal. Useful, working software is your goal. Preferably written in such a way that other people can read and change it.

(As as aside, code clarity means more than short functions and correct indentation. I've seen plenty of code, usually in C, that was small, neat, elegant... and you couldn't figure out how it did anything. Talk about missing the whole point.)

Unit testing is just another tool in the toolbox. Used at the right place and time, it can do an excellent job. Shoehorned in for the sake of ticking a checkbox, it will just get in the way. And don't even get me started about writing code to satisfy the tests as opposed to, you know, the end-user.

Nobody cares what tools a carpenter uses if the furniture they make is ugly, heavy, and requires climbing carefully over the nightstand to get in bed.

That said, I did actually use TDD exactly once. It was for a library of largely independent functions, the requirements were simple, and my tests were mostly there to document usage. That's another good case for tests, by the way, and in fact the D compiler also supports it directly. Making sure your example code runs, and runs correctly, can save you from a lot of embarrassment down the road.

Just focus on delivering already, before you forget why you were writing all those tests in the first place.

Tags: programming, philosophy

Comments? Tweet