CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 3 of 6 · 1 min read

Good duplication

Look the same, but belong to different people.

Module 1 showed that two copies of code may look alike only by chance. The pay method and the report method shared regularHours(). They belonged to different actors, so the sharing was the mistake.

So the test for DRY is not "do these lines look the same". It is "is this the same fact?". If two pieces will always change together, they are one fact and should be one piece of code. If they could change separately, they are two facts that happen to match today.

A useful habit is the rule of three. The first time, write it. The second time, tolerate the copy and notice it. The third time, remove the duplication, because now there is enough evidence to see what the shared part really is. This habit is common practice and not a quotation from the books.

Premature joining is also costly in another way. A shared helper with many flags, written to serve two callers that are slightly different, becomes harder to read than two copies.

Common mistake

Merging code because it looks the same, without asking whether it will change for the same reason. A wrong abstraction is harder to undo than a repeated line.

Check yourself: 1. What question should replace "do these lines look alike"? 2. What is the rule of three?