Lesson 1 · Unit 02
Duplication
One fact, one place: and when a copy is fine
What you practise
- The same knowledge in two places, extracting the shared part, the rule of three, and the wrong abstraction that is worse than the copy
Try a question from this lesson
Pick one
You notice the same four lines for the second time in a codebase. What does the rule of three advise?
Correct answer
Note it, and extract when a third copy appears
Why
Two copies rarely show which parts are truly the same and which only match today. A third use reveals the real pattern. Extract too early and you guess at the abstraction; wait too long and a fix misses a copy.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
One fact, one place
Every piece of knowledge should have a single home in the code: a tax rate, a formula, a rule.
Then a change is one edit, and two parts of the program cannot disagree. People call this DRY: don't repeat yourself. It is about repeated knowledge, not about lines that happen to look alike.
TAX_PERCENT = 25
def with_tax(net):
rate = 100 + TAX_PERCENT
return net * rate // 100
cart = with_tax(200)
invoice = with_tax(200)const TAX_PERCENT = 25;
function withTax(net) {
const rate = 100 + TAX_PERCENT;
return net * rate / 100;
}
const cart = withTax(200);
const invoice = withTax(200);const TAX_PERCENT = 25;
function withTax(net: number): number {
const rate = 100 + TAX_PERCENT;
return net * rate / 100;
}
const cart = withTax(200);
const invoice = withTax(200);9 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 1× true or false
- 1× multiple choice
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.