The true value of TDD (and good design)

Today I had to tear apart and refactor one of core pieces of tool I’m working on. Oh, and I had to do it fast.

At first, I was like: “Hey, you can’t change that, it was supposed to stay the way it is now!”. Next I started to refactor, changing one by one, all the pieces I needed to change in order to achieve desired effect. I was refactoring, compiling, testing… and again refactoring, compiling, testing…. And ultimately when all tests were once again green – I knew I was done. I felt confident.

Thanks to TDD and good design I had, I was able to change big piece of code very quickly, and without causing everything to fall apart. I’ve read about how TDD gives you confidence, how good design helps, I’ve been there before, but in this moment when I was starring at all green tests, it all felt so apparent, it was almost magical.

  • If you’re really doing the refactoring (changing the code without changing the behaviour) this should work better:
    – write test for the old code,
    – refactor,
    – test the new code

    On the other hand if you are restructuring the code, which is not refactoring, your strategy could be the only possible if the old code is not testable.

  • Right, I should have noted that I had pretty good test coverage. So my workflow looked more or less like this:

    – Run tests to make sure everything plays nice.
    – Refactor/change/add a piece
    – Compile and test
    – Review the tests that don’t pass, and either fix the code to make the test pass, or (in cases where I changed the code in such a way that test makes no sense in current shape) change the test. Possibly add more tests
    – Repeat above step until all tests pass

    But as you can see, I was not only refactoring in strictly Fowler-esque sense of the word, but I also needed to add some functionality and replace a big chunk of code as well.

    Fortunately the code was quite well structured and loosely coupled, so it wasn’t painful to change and test.