What about Once and Only Once?
I fully understand,appreciate, and follow the Once and Only Once (OAOO) mantra of the agile movement. But this mantra has to be taken in its context — it is a part of the definition of SimpleDesign. SimpleDesign means to write the system such that these things are true:
- Code is appropriate for its audience
- Communicates its intent clearly
- Each concept is represented once and only once
- Expressed in as few classes as possible
- Expressed in as few methods as possible
in that order! If you look carefully at that list, communication is #2 on the list, while OAOO is #3. This means the communication trumps a little duplication. Part of becoming more experienced at TDD, Refactoring, and Simple Design is knowing when it is appropriate to leave in a little duplication to enhance communication. And I think this is one of those times.
There is definitely a price to pay for it, however. Since the setup and teardown logic are potentially duplicated among a bunch of similar unit tests, you have to change each of them individually should the logic change. I’ve paid that price a bunch of times in the past, but I still believe that the gains in communication outweigh the cost of the replicated changes. YMMV