When you are done with development, writing tests is painful and boring. You are stuck in what I call the D3-dilemma (Development Driven Development Dilemma):
The 😈 tells you — “You're done! Of course your function is working! Let’s release this right now and start the next exciting project.”
The 👼 calmly reacts — “You know you should write those tests. You have to validate your code and make it easier to maintain for your fellow developers.”
Truth is, it's painful to stop an exciting project when your colleague sees a failure in a portion of code you've written a while ago and forgot about.
Test-driven development (TDD) is a practice where software requirements are converted to tests before software is fully developed. This allows to track the software development by repeatedly testing the software against all test cases.
I had my TDD enlightenment on November 10th 2022. It's been a game changer in how I approach projects. Here’re four reasons why you should try it:
- TDD prevents you from rewriting your code. In the flow of coding, you can write a function, take a break, and realise the function wasn’t needed. TDD forces you to 1) add a step where you focus on translating the product requirements into code requirements, and 2) think about how the code should be structured prior to implementing it.
- TDD allows you to be lazy: “Translate the product requirements into tests and forget about them.”
- TDD gamifies coding. Once you’re done with writing tests, your target number one becomes stupid and simple: make all tests green ✅.
- TDD makes debugging lighter. It's harder to run tests at the end because you get multi-domain errors all at once, e.g. test setup errors, main logic error, and sub-functions errors. With TDD, you control the type of error you get because you can progress step by step:
- Write the test setup functions, run the tests to validate them.
- Implement one part of the main function, make sure the related test is green.
- Implement another part of the main function, make sure the related test is green.
- etc until everything’s implemented.
TDD works particularly well in two situations:
- You have an important bug. Don't solve the bug! Highlight the bug with a test and solve the test.
- You’re working on the backend. Frontend can often be tested visually and fast. Backend is much less tangible. TDD artificially creates a tight feedback loop when you develop code that’s not visual.
Note that TDD works poorly when you’re unclear about how to implement your code. Writing a good tech spec with a section on how to test your code is a good, or perhaps a necessary, step to grasp the full power of TDD.
<aside>
👋 Here’s my dev-to-dev advice: make TDD a habit whenever you can. It makes my life easier, and it'll make yours too.
</aside>