If you aren’t familiar with it, test-driven development (TDD) is a software development practice where you write tests before you write application code.
TDD is something most computer science students are taught, but are never actually required to use. And you can get away without doing it for most of your coursework. (I have some thoughts on that here.)
At any rate:
Good tests make good documentation – both for you and anyone who might come onto your project later. Test frameworks like Jasmine and Mocha read like plain English. Name your tests in a way that describes the tested function’s behavior in a particular circumstance.
You’ll code faster. Even if writing a correct function implementation is difficult, pre-written tests will give you a clear target to hit.
You’ll code correctly faster. Keep your test runner open to get continuous feedback on your work. This will get you to a correct implementation faster than coding an entire module at once and then testing it.
You won’t forget to write the tests. Code without tests should make you uneasy, period. A comprehensive, passing test suite is reassurance to you and other developers that your code (probably) won’t break.
It provides a solid starting point for later work. Similar to #1. Also, if you pick a project back up after a few months, you’ll forget how most of the code works. Tests can be a reminder, and a tested code base can be a fallback if you suddenly break things.
It pushes you to write cleaner code. Long, complicated functions are hard to test. Simple tests and clear descriptions will naturally lead to shorter, more readable application code.
You’ll write more meaningful tests. With code already written, it’s easy to write tests that just pass instead of tests that confirm useful functionality. Imagine if your math professor only tested you on things you already knew – that wouldn’t be very useful!
Do you have more reasons? Drop a comment below!
- This is part of a 6-part series on clean code. It’s some of the most valuable reading I’ve ever done as a developer.