TDD provides focusTDD helps me avoid mental rabit trails of nice-to-haves and performance improvements.
Today while doing some live stream coding I was reminded once again of one of the often-overlooked benefits of Test-Driven Development.
More than once, as I was coding, I’d realize there was a use case I hadn’t yet considered, and I’d start down the mental rabbit trail of fixing that. Take for example the iterator I was writing, to read various verions of a file from disk. The ideal implementation would keep just some sort of cursor in memory, to know which file to open for the next iteration. But my current code didn’t support this.
After musing about this for a while, and the best way to make an efficient iterator, I remembered that my immediate goal was to make my test pass when it requested two files. The easy way to do this is to just read both files into memory, then return an array of files.
Make it work, make it right, make it fast.
— Kent Beck
So after catching myself running down this rabbit trail of optimization, I let TDD reign me back in, and focus on the problem at hand. I wrote the necessary code. My tests pass now.
Now when I’m ready, I can work on refactoring the code to be more efficient.
TDD and throw-away code
If I had started with test-first approach, I would have saved half a day or so.
How I know when I'm done
When I work on a project that relies on manual verification, I'm never confident. I never feel sure of the work I'm doing.