Video in progress

What does the DRY principle require, and how does overdoing it cause harm?

DRY (Don't Repeat Yourself) means every piece of knowledge or rule should live in one place in the system, so a change happens in one place. But merging code that only looks similar by accident and means something different creates needless coupling.

📖 Answer

A good use: the VAT rate is 12%. If it is written as 0.12 in ten places, then when the rate changes, one of them will surely be forgotten.

public final class Tax {
    public static final BigDecimal VAT_RATE = new BigDecimal("0.12");
    private Tax() {}
}

A bad use: the validation of User and Product both have a check "name is 3-50 characters". You merged them into one validateName. A month later, product names are allowed up to 120 characters, so now an if (isProduct) gets added to the shared method, and two independent rules are tied to each other.

A practical test: do the two pieces of code change for the same reason? If yes, merge them. If they only happen to look the same today, leave them.

Many developers follow the "rule of three": you write it the first time, copy it the second time, and extract it to a shared place the third time. By then it is clear whether the similarity is real or not.