TDD by Example Chapter 6: Equality for All, Redux

Summary

In this chapter the mess created in the previous chapter is cleaned up. The first part tackled is the duplication of the equals in the Dollar and Franc classes. Beck decides to extract the calculation for equals() into a super class Money.

The rest of the chapter is a step by step refactoring. Beck makes a point to note how small the steps are and how he runs the tests after each step. Even when he takes a slightly larger step, he points out how he could have taken a smaller step.

He also makes a point to show that he removed the duplication between the implementations of equals by adding more duplication. After extracting the implementation of equals from Dollar into Money he makes an effort to have the implementation in Franc match exactly the one in Money. It turns out that the only difference is the type of the object but when they are exactly the same removing one for the other is safer.

In the middle of this refactoring, Beck goes on a bit of tangent about the need for tests when refactoring. He expects that most of his readers will be faced with having to refactor code without adequate test coverage and he suggests that they add the tests they need to refactor safely.

Commentary

Refactoring is the design step in the TDD cycle of Red/Green/Refactor. This is what jumped out to me while reading this chapter. One of the biggest benefits of the tests is that they allow you to change the arrangement of your code knowing that you haven't changed what it does.

You can experiment. You can play. If you break something the tests will tell you.

This is why the speed of the tests are so important. The faster the tests run, the more you can play. More play increases the chance that you will discover a good design.

However, there's a limitation to this. Doing the refactoring in small steps, running the tests after each step, and only moving forward if they pass limits the kinds of ideas I can have. They must be ideas that keep the tests passing. The tests are the walls at your back, but they may also box you in.

What if you could just play with designs without having to worry about getting tests to pass right away? A way to do this is to explore your design ideas outside of code. You could draw diagrams. You could write prose.

The tests can then be used to verify that your diagrams or prose lead to something that works.