Nic Jackson in Coding 2 minutes

A surgeon would always operate with eyes wide open : Why you need unit tests

This is just a short post but I wanted to explain an experience I had this week which reminded me why unit tests are so important in a codebase. We are working on creating a Swift package to send StatsD statistics as part of an experimental microservice we are building. Unfortunately the language is in the early stages and quite a lot of the networking stack in Core Foundation is not yet implemented and available for Linux.

First do no harm

After a little digging on the old interwebs I found an open source implementation of a socket class which wraps some of the standard libC libraries. Unfortunately this only supports TCP not UDP but being a good contributor to the open source community I am more than happy too add this support. This was not as smooth as it should have been, the first stumbling block I had was the absolute fear of modifying the existing code due to an inability to accurately test it. Whilst the existing logic for TCP was not so complex the process of adding a new protocol changes things quite substantially and I was really uncertain that I would not break the hippocratic oath (first do no harm), this almost stopped me dead in my tracks.

The code was well written and clean but that is not really enough, if the code had a test suite then I would have been able to make my incision with confidence. In addition to this instead of having to read through the code reverse engineering it in my head these very same unit tests would have given me this information.

You don’t write code for yourself

Open source is all about collaboration, when open sourcing a project if you would like people to contribute do yourself a favor and remember that you write code for someone else to read, not to read yourself. Implementing good practice like clean code and TDD in your projects will greatly help your future contributors and therefore boost the success of your project.