DRY, KISS, YAGNI
Three rules of restraint in code: do not repeat the same knowledge (DRY), prefer the simplest solution (KISS), do not build what is not needed yet (YAGNI), and their limits.
- 25 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
DRY: what is it?
Show the answer
The rule that each piece of knowledge in the system (a business rule, a rate, a format) has a single authoritative representation.
The acronym stands for “Don't Repeat Yourself”. It targets duplicated knowledge, not every resemblance between two pieces of code.
Which fix applies DRY to this code?
```python
def prix_ttc_dvd(prix):
return prix * 1.2
def prix_ttc_jeu(prix):
return prix * 1.2
def facture(total):
return total + total * 0.2`- Define a constant
TVA = 0.2and use it in the three functions - Merge
prix_ttc_dvdandprix_ttc_jeuinto one function, leavingfacturealone - Add a
# VAT 20%comment above each function - Rewrite each function on a single line
Show the answer
Define a constant
TVA = 0.2and use it in the three functionsThe VAT rate is one piece of knowledge written three times, in two forms (1.2 and 0.2). Merging two functions leaves the repetition in
facture; a comment adds one more to keep up to date.- Define a constant
If the invoice-number format is coded again in four modules, changing it means finding them all: DRY asks that each piece of … have a single … in the system.
Show the answer
If the invoice-number format is coded again in four modules, changing it means finding them all: DRY asks that each piece of knowledge have a single representation in the system.
A named function or constant becomes the single source of that format: it is changed in one place, with no risk of missing a module.
KISS: what is it?
Show the answer
The rule that, between two solutions that meet the need, you keep the one that is simplest to read, test and maintain.
The acronym stands for “Keep It Simple, Stupid”. Simple does not mean short: an 80-character regular expression is brief and unreadable.
Shipping fees and the late-payment penalty were both 5%. They were merged into one
taux()function. The penalty rises to 8% after a legal decision, and the shipping fees change too. What is the cause, and the fix?- Accidental duplication: two different pieces of knowledge; separate them again
- DRY violation: the VAT rate should have been merged too
- Premature abstraction: add a
typeparameter totaux()to tell the cases apart - KISS violation: the 5 should have been written directly everywhere
Show the answer
Accidental duplication: two different pieces of knowledge; separate them again
The two values were equal by chance, and do not change for the same reason (transport, the law). A
typeparameter keeps the artificial link while hiding it. DRY targets identical knowledge, not identical values.