Hi Jmv38,
The TDD cycle is red/green/refactor. The “redesign” phase comes every few minutes, as we look at the code we’ve just made work and see how to revise it.
In this example, much of the revision came a little ways in (remember this is only 40 lines of code and about 25 of test so far) where we got the idea of pulling out the operations into a separate function table. Happens we got that idea from dave, but we could have had it from our pair partner, our own brain, wherever. What we saw in the code was the repetitive character of the code for each operator key. We had that code that looked like this:
if key == "*" then
self.op = function(d,t) return d*t end
self.first = true
elseif key == "/" then
self.op = function(d,t) return t/d end
self.first = true
And we were troubled by the duplication. So we extract it into some structure, extract again, and finally wind up with the individual arithmetic operations in a table and everything else in a doPending()
function that does all the common bits.
What’s happening here is that we’re identifying ideas (abstractions, if you like the word) and building code to represent them. We create generality, just a bit at a time, as we need it.
Turns out that the more we do in this mode, bit by bit, the closer the program stays to a good structure. We don’t always manage that, though, and sometimes things get a bit out of hand – and we want to rewrite.
Rewriting is always very hard, as you say. In my experience, in business it is rarely really the right thing to do. The reasons include that it takes a long time before the people paying see progress, and generally whatever made us do it poorly last time is still there, so we wind up with another ball of worms.
It’s better (though sometimes less fun) to refactor the program from not so good to better, and that can always (always) be done incrementally. That way, we get better code and more features together. This keeps the money people happier.
An article about that is here: http://xprogramming.com/articles/refactoring-not-on-the-backlog/
However, especially when we are programming for fun, there is great value to writing things in different ways. I still find that rewriting the whole program is a pain, so I try not to do it. But rewriting bits in different ways, we can learn a lot about our design, and about the language.
TDD is not about not designing … it is about designing all the time, and improving the design all the time. If we improve the design all the time, it stays alive longer. And if we engage our code in the design process, we tend to get cleaner and simpler designs.
YMMV, of course. I’m not here to tell anyone what they should do. I’m here showing you what I do and what happens, and I’m willing to chat about why I do it and such as long as it’s useful and interesting.