For the past few weeks and months, my good friend Brian Button has been posting a six part series called “TDD Deep Dive” which is one of the better TDD-by-example explanations you can read in less than an hour. If you haven’t read it yet, go read it now. (Links: Part 1, 2, 3, 4, 5, 6.) _place_holder;Then come back here and continueΓÇª
_place_holder;Well, Brian has done it again. This time with a very cool post titled “Extreme” Refactoring - The Video Store Revisited. In this essay–almost 1,800 words of text, plus just under 1,000 lines of code–he takes the example used in Martin Fowler’s Refactoring book and takes it through a truly extreme refactoring process.
He begins with three goals in mind:
- Methods should be 1 line long. Anything longer than that needs to be looked at closely.
- Aggressively eliminate all duplication, specifically duplication involved with iterating over containers several different times in similar ways.
- Use no private methods.
And then works to make it happen. Using the baby-step approach he used with me, he works through one little piece at a time. Extract Method here, Extract Superclass there. A little of thisΓÇª a little of that.
And when he is done, the code certainly doesn’t look like Martin’s anymore. Is it better? Even Brian isn’t sureΓÇª
Now for the questions. Is this code more clear than the original Customer class? I’m not sure. In some senses it is. If I want to go see how the statement is generated, I can now go look at a RentalStatement class and see it. Looking ahead a bit, knowing that one of the changes Martin talks about in his book is that we need to support an HTML statement as well as a text statement, so by creating the RentalStatement class, we’re well prepared to make that change. I’m never sure if the ReplaceExternalIterationWithInternalIteration ever makes code more clear, but it does eliminate duplication.
I’m not sure that I would ever go this far in real life, but it is nice to know that I could.
But the process is very cool, very educational and something we all should strive for.