DRY, KISS and YAGNI
Learn three short rules that keep designs honest: do not repeat knowledge, keep things simple, and do not build what you do not need yet, and learn when each rule can go wrong.
Imagine packing a suitcase for a three-day trip. If you pack three copies of the same shirt, the case becomes heavy for no reason. If you pack a complicated folding system with twelve compartments, you will spend more time packing than travelling. And if you pack winter clothes "in case it snows" on a trip to a tropical beach, you carry a load you will never use.
Software design has the same three traps, and each has a short name: DRY, KISS and YAGNI. They are easy to remember and powerful, but also easy to misuse. This lesson explains what each one really means, shows an example, and, most importantly, tells you when each rule goes wrong.
01DRY: Do not Repeat Yourself
DRY says: every piece of knowledge should live in exactly one place. If a rule or a fact appears in many places, then when it changes, you must find and update all of them, and you will miss one.
Here is a small example. A shop adds 18 percent tax to prices:
long cartTotal = subtotal + subtotal * 18 / 100; // in the cart
long invoiceTotal = amount + amount * 18 / 100; // in the invoice
long quoteTotal = price + price * 18 / 100; // in the quoteThe number 18 is a piece of knowledge: "the tax rate". It is written three times. When the government changes the rate, someone must remember all three places. One will be forgotten, and customers will see different totals on the cart and on the invoice.
The fix is to give the knowledge one home:
public final class Tax {
private static final long RATE_PERCENT = 18;
public static long withTax(long amountInCents) {
return amountInCents + amountInCents * RATE_PERCENT / 100;
}
}
// Everywhere else
long cartTotal = Tax.withTax(subtotal);
long invoiceTotal = Tax.withTax(amount);
long quoteTotal = Tax.withTax(price);Now a rate change is a one-line edit.
The trap: DRY is about knowledge, not about text
Many beginners hear DRY and start merging any two pieces of code that look alike. That is a mistake. Two pieces of code can look the same today and still be different knowledge that changes for different reasons.
Suppose students get a 10 percent discount and senior citizens also get 10 percent. If you write one constant DISCOUNT_PERCENT = 10 and use it for both, you have joined two unrelated rules. Next month the seniors' discount becomes 15 percent, and you must untangle the code to avoid changing the students' discount by accident.
private static final int STUDENT_DISCOUNT_PERCENT = 10;
private static final int SENIOR_DISCOUNT_PERCENT = 10;A good question to ask before merging: "if one of these changes, must the other change too?" If yes, they are the same knowledge: merge them. If not, they only look alike: leave them separate. A wrong merge is usually more painful than a little repetition.
Loading the rest of the lesson…