Part 2 of 6 · 2 min read
DRY
Each piece of knowledge lives in one place.
Think of a phone number written on ten sticky notes around an office. When the number changes, someone will miss one note, and a caller will get the wrong line.
The idea comes from Dave Thomas and Andy Hunt, and CC calls duplication one of the most important rules in its book. CC says that each instance of duplication is a missed chance to create an abstraction, and that it may be the root of much that goes wrong in software. Repeated code must be changed in many places when the rule changes, and each place is a chance to forget one.
CC lists forms of duplication from obvious to subtle.
- Identical lines pasted in many places. Replace them with one method.
- The same
iforswitchchain repeated across modules, always testing the same cases. Replace it with polymorphism (module 2 of this level). - Different code that follows the same steps. Use the template method or strategy pattern (Level 4).
A small example makes it concrete. Booking and moving a booking both check the time slot. Written twice, the checks drift apart. Written once, they cannot.
static String slotError(int start, int end) {
if (start < 0 || end > 24) return "outside the day";
if (end <= start) return "end must be after start";
return null;
}
static String book(int s, int e) {
String err = slotError(s, e);
return err == null ? "booked " + (e - s) + "h" : err;
}
static String move(int s, int e) {
String err = slotError(s, e);
return err == null ? "moved to " + s + "-" + e : err;
}
book(9, 11) returns "booked 2h". move(9, 8) returns "end must be after start". book(-1, 3) returns "outside the day". A change to the rule, such as an opening time of 8 o'clock, is made in slotError and applies to both.
DRY
DRY stands for "don't repeat yourself". It says that each fact or rule should be written in exactly one place.
Example: the slot check written once in slotError.
Check yourself:
1. What does CC say each instance of duplication is?
2. What replaces a repeated if chain?
3. Where is the opening-time rule changed in the example?