Okay, I admit it. Sometimes I write unit tests second instead of first. I also bite my nails and rest my elbows on the dinner table. But when I’ve got a bug to fix, and I’ve already found the offending line, I can hardly resist the urge to just… just… change it. I’ll follow up with unit tests afterwards, promise.
I admit this to you because admitting my wrongs is a step towards rehabilitation. I admit this to save you pain. Learn from my example. Test-second is so much less efficient than test-first. Consider the following workflow:
- Reproduce, identify, debug the issue.
- Fix the code.
- Compile and try it out.
- Write a test that proves I fixed it.
- Compile and run the test.
- Change the code back to make sure my test really proves what it is trying to prove.
- Compile and see the test fail.
- Re-fix the code.
- Compile and see the test pass.
I humble myself before you. How much time am I wasting there? It’s embarrassing.
There’s also a subtle point in step 1. What if I could use unit tests instead of the debugger to find the issue? That will be faster, too.
We can do better:
- Reproduce the issue and formulate a theory.
- Write a test that exercises the theory.
- Compile and see the test fail, corroborating the theory.
- Fix the code.
- Compile and see the test pass, validating the theory.
Perhaps you can relate. Perhaps you even bite your nails, too. I won’t judge. Flog me or join me, the comments are open: Confess your bad habits (um, your unit-testing bad habits, please), and commit yourself to improvement. I challenge you to improve your efficiency and write your unit tests first, even—especially—for the little bug fixes.