Chapter 19. Once and Only Once

The phrase Chapter 19 is a reminder of a goal of refactoring. Every piece of knowledge within the system should be represented in a single, well-known place. Eliminate repetition.

The Pragmatic Programmer, by Andrew Hunt and David Thomas (Addison-Wesley), suggests a slightly different rule: Don’t Repeat Yourself (DRY). The difference is subtle. Once and Only Once suggests eliminating duplication through refactoring. It applies to code and design concepts. The DRY principle goes further. It applies to code and design but also other project artifacts. For example, if you find yourself performing the same steps while integrating, automate them. Both principles apply; solve a problem once and for all.

Duplication and repetition are warning signs. Any time knowledge is duplicated, it’s possible for the versions to fall out of sync, as is often the case with code and comments. Repeated code is an obvious opportunity for refactoring—it can signify that your abstractions should be made more powerful or that your code can be generalized.

Repetition and duplication produce inertia. It takes longer to make a change that requires touching several different pieces of code. It is more difficult to make a change if the responsibilities are scattered throughout the code. You’ll have to rely on your memory. Comprehensive tests may not help: if every duplicate section has its own tests, you can’t make a change and rely on test failures to identify everything you need to ...

Get Extreme Programming Pocket Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.