How do people doing TDD handle loss of work when doing major refactoring

refactoringtdd

For a while I have been trying to learn to write unit tests for my code.

Initially I started out doing true TDD, where I wouldn't write any code until I'd written a failing test first.

However, I recently had a thorny problem to solve which involved a lot of code. After spending a good couple of weeks writing tests and then code, I came to the unfortunate conclusion that my entire approach was not going to work, and I would have to throw out two weeks work and start again.

This is a bad enough decision to come to when you've just written the code, but when you've also written several hundred unit tests it becomes even more emotionally difficult to just throw it all away.

I can't help thinking that I've wasted 3 or 4 days of effort writing those tests when I could have just put the code together for proof of concept and then written the tests afterwards once I was happy with my approach.

How do people who practice TDD properly handle such situations? Is there a case for bending the rules in some cases or do you always slavishly write the tests first, even when that code may turn out to be useless?

Best Answer

I feel there are two issues here. The first is that you didn't realize in advance that your original design may not be the best approach. Had you known this in advance, you may have chosen to develop a quick throw-away prototype or two, to explore the possible design options and to assess which is the most promising way to follow. In prototyping, you need not write production quality code and need not unit test every nook and cranny (or at all), as your sole focus is on learning, not on polishing the code.

Now, realizing that you need prototyping and experiments rather than starting the development of production code right away, is not always easy, and not even always possible. Armed with the knowledge just gained, you may be able to recognize the need for prototyping next time. Or may not. But at least you know now that this option is to be considered. And this in itself is important knowledge.

The other issue is IMHO with your perception. We all make mistakes, and it is so easy to see in retrospect what we should have done differently. This is just the way we learn. Write down your investment into unit tests as the price of learning that prototyping may be important, and get over it. Just strive not to make the same mistake twice :-)