Code duplication is the presence of multiple substantially similar copies of an implementation. Repeated code enlarges programs, complicates maintenance, and creates change leaks: one copy may be missed or changed differently. section 2.3.3
Duplication often exposes a design problem rather than a typing problem. Similar methods, algorithms, or coordination sequences create parallel places where behavior must be corrected and extended. section 2.3.3 section 10.2.2
Common forms of code duplication include:
- Repeated type-specific search methods in a catalogue, accompanied by runtime isinstance checks. section 2.3.3
- Repeated play and sound implementations across toy subclasses, where shared behavior belongs in one reusable implementation. section 7.3.1
- Repeated report-generation steps and shared header and footer operations across baseball and volleyball reports. section 8.1.2
- Repeated algorithm results such as the stadium venue across sports subclasses, making reuse and later changes difficult. section 8.2.2
- Repeated iteration and player-printing logic for lists, generators, and dictionaries, coupling reporting code to storage details. section 11.1.2
The Don’t Repeat Yourself principle recommends sharing one copy of repeated behavior as a separate function or cohesive class. The right refactoring target is cohesive behavior, not arbitrary text similarity. section 2.3.3
Refactoring can proceed incrementally: identify common operations, extract one shared implementation, delegate variant behavior where needed, and then test the resulting common and custom paths. section 7.3.2 section 8.1.1
Reports before refactoring
BaseballReport and VolleyballReport each implement generate_report(), _print_header(), and _print_footer(). Because both reports follow the same sequence, a later change to that sequence requires parallel edits. A Template Method can centralize the fixed workflow while leaving sport-specific steps customizable. section 8.1.2 section 8.1.1
Shared algorithms
ToyCar and TrainSet both implement rolling, while ToyCar and ModelAirplane both implement the same engine sound. Separate play-action and sound classes provide one sharable copy, although multiple inheritance still hardcodes each toy’s behavior. section 7.3.1 section 7.3.2
Figure 7.3 Each play action and sound behavior is a separate class. Each Toy subclass has an is-a relationship with the Toy superclass and an is-a relationship with the play action and sound classes. By sharing these classes, we’ve eliminated some code duplication, but each toy still has hardcoded behaviors.
Compare the shared behavior classes with the toy subclasses that still hardcode behavior choices. section 7.3.2


