Tuesday, September 28, 2004 8:36 AM
pdbartlett
Idea of the day #2 - Test Driven Maintenance
(This was actual the idea of a day several weeks ago, but I've been a bit busy...)
We all know that Test Driven Development follows the "red, green, refactor" mantra, and in that idealised world when we're all writing brand spanking, new, state of the art code then that is all well and good.
However, back in the real world you may have a large body of existing code with incomplete (in previous assignments "incomplete" would have been something of an understatement!) unit test coverage. Wouldn't it be nice is we could fix bugs and/or improve code quality with low risk of regression, and bolster our portfolio of unit tests at the same time? Well, I think we can, if we approach it right...
First consider what I shall call Test Driven Bug Fixing, which follows the pattern "green/red, fix, green/green". Now unless you're a mind-reader (and if so I apologise if you're reading mine now!) that's not going to make a lot of sense, so here's the approach in a fuller form:
- Write unit tests for the mainline case and the "buggy" case
- Run them against the existing code, and:
- If you get "green/red", go to stage 3
- If you get "red/red", and the test is OK, extend the scope of the bug and go to stage 3
- Otherwise, go back to stage 1
- Fix the bug
- Re-run the tests, and:
- If you get "green/green" go to stage 5
- Otherwise go back to stage 3
- (Optional) Refactor the code and go back to stage 4
Then we have Test Driven Code Improvement, which follows the pattern "green, refactor, green". This is hopefully somewhat more obvious, so I won't spell it out in any more detail, though naturally I'll reconsider if comments state otherwise.
The main benefits I see here are:
- reducing risk of regression, both at the time of the initial change and in the future (fixes are often "undone" by people who remake the same mistake as the original developer)
- building up a portfolio of unit tests that will eventually support more adventurous system-wide refactorings
- building up the tests in a priortised manner so that the ROI is practically immediate (very manager-friendly!)
I doubt these ideas are new, but I'd certainly not come across them in exactly this form.
Comments, anyone?