Sometimes, people ask me (James) how I got started doing test-driven development. I want to relate this story because as a result of this experience, I finally believed that a series of small steps, verified each time by tests, could actually lead to a better solution. Up until this point, I knew the rules but not how to apply them.
It was December of 1999. I was at Object Mentor, and we were in the midst of the first XP immersion class. Kent Beck, Ron Jeffries, Martin Fowler, Robert C. Martin, Michael Hill, Fred George, Alan Francis, and others were my companions. Needless to say, it was an incredible week, not so much from the perspective of a class, but from being around such an awesome array of talent all focused on this thing called Extreme Programming. Besides participating in the class, I was working on a new Java class that I would be presenting the following January. I was trying to incorporate aspects of refactoring and test-first programming using JUnit ( http://www.junit.org ) into the class. My thought was to write an awful program and then use it to teach the concepts of refactoring. (That same awful program, implemented in C#, is the basis for Chapter 3, Refactoring ”By Example. )
I was working alone, and the staging of the example was not working well because it turns out that my refactoring steps were much too large. Kent came over and asked what I was doing after noticing me working on code by myself ; I told him that I was trying to work out an example of refactoring for my upcoming class. After looking at what I did, he told me he thought I should start over. Instead of walking away, he offered to sit down and help me. During the next hour or so, the whole idea of the small incremental changes leading to a better solution became a reality. This awful code was transformed into something that was very clear and easily understandable.
It is only after I spent that time working with Kent directly that I began to understand just how small the steps were that Kent, Ron, and Martin were talking about. In fact, we thought that this in itself would be a useful activity for the whole class to see the following day. So, Robert Martin went home that night and constructed some UML diagrams around the code and came up with a slightly different implementation of the same algorithm that Kent and I refactored in front of the class the next day. For a couple of hours, we walked step- by-step through the code ”making the smallest of changes and then running the tests to make sure that we did not break anything. When we were finished, someone said that we had made 40 separate changes to the code. The code was so much clearer that it was remarkable . Alexei and I have used the same problem that taught me so much during the class as the sample in Chapter 3 so that you can also benefit from that experience.