Last Updated: February 25, 2016
·
786
· austinkeeley

The hidden benefit of test driven development

Eat your vegetables, stay in school, and write unit tests before writing your code. We've heard it so many times.

We probably also don't exactly follow it, but hey, that's reality. The main benefit of test driven development is that it increases confidence in the predictability of the code. That's fancy power point talk for it makes sure your code still works when things change. There's a second side of test driven development that's not as obvious: it will make you design better code. That's my theory at least; simply writing good unit tests means your skills as a designer get better.

Here's my story: I inherited a JavaEE project that I wasn't exactly thrilled about. No unit tests, no documentation, and build script that only seemed to work if your sacrifice was accepted by the pagan gods and you had the right combination of .jar files. In short, it wasn't going to be fun.

I decided the first thing I was going to do would be to write unit tests. That way, I could tell if my changes would break anything. I quickly discovered this was an impossible task; the code just wasn't written to be unit tested. The only public methods returned void and there were no entry points there that I could use to test the code without having dependencies on a huge number of external resources. At that point, I would just be writing full integration tests and not the unit tests I wanted. Around this time, I found that the content of the code was also pretty bad; a lot of tightly coupled components that didn't adhere to any declared interface. I began thinking about how all this could really be improved with a good framework, like Spring, that could break the code into small reusable components that are, by their nature, very unit testable. Dependency injection requires interfaces, and those, my friends, are very good things. Even if you're not using dependency injection or a framework, if your code can be unit tested, it's probably not half bad. And even if it is, at least someone can come in later and clean things up.

So here's the takeaway: writing unit tests forces you to write loosely coupled code, and loosely coupled code is better designed code. Also, get 8 hours of sleep. That stuff's important.