LOW-LEVEL DESIGN · DESIGN PRINCIPLES · PRINCIPLE · 13 OF 48

DRY, KISS and YAGNI Explained with Java Examples

Three everyday design rules: keep each piece of knowledge in one place (DRY), choose the plainest design that works (KISS), and do not build for needs you only imagine (YAGNI). Plus when DRY goes wrong: accidental duplication, the wrong abstraction and helpers that grow flags.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 111 lines, with a small main() demo. Save it as DryKissYagniDemo.java, then run javac DryKissYagniDemo.java && java DryKissYagniDemo.

import java.util.List;

/**
 * DRY, KISS and YAGNI in a food delivery app.
 * Money is in paise (1 rupee = 100 paise) so there are no rounding errors.
 */
public class DryKissYagniDemo {

    // ---------- Before: the fee rule is copied into two classes ----------

    static final class CopyPasteCheckout {
        long total(long itemsPaise, int km) {
            long fee = 4000 + km * 800L;
            if (itemsPaise >= 40000) {      // updated to the new free limit
                fee = 0;
            }
            return itemsPaise + fee;
        }
    }

    static final class CopyPasteReceipt {
        String line(long itemsPaise, int km) {
            long fee = 4000 + km * 800L;
            if (itemsPaise >= 50000) {      // forgotten: still the old limit
                fee = 0;
            }
            return "Delivery fee: " + rupees(fee);
        }
    }

    // ---------- After (DRY): one home for the customer fee rule ----------

    static final class DeliveryFee {
        static final long BASE = 4000;
        static final long PER_KM = 800;
        static final long FREE_FROM = 40000;

        long forOrder(long itemsPaise, int km) {
            if (itemsPaise >= FREE_FROM) {
                return 0;
            }
            return BASE + km * PER_KM;
        }
    }

    static final class Checkout {
        private final DeliveryFee fee;

        Checkout(DeliveryFee fee) {
            this.fee = fee;
        }

        long total(long itemsPaise, int km) {
            return itemsPaise + fee.forOrder(itemsPaise, km);
        }
    }

    static final class ReceiptMailer {
        private final DeliveryFee fee;

        ReceiptMailer(DeliveryFee fee) {
            this.fee = fee;
        }

        String line(long itemsPaise, int km) {
            return "Delivery fee: " + rupees(fee.forOrder(itemsPaise, km));
        }
    }

    // ---------- Not merged on purpose: a different fact (accidental duplication) ----------

    /** The rider rate is set by operations, not marketing. It equals the customer rate today by chance. */
    static final class RiderPayout {
        static final long PER_KM = 800;

        long forTrip(int km, boolean raining) {
            long pay = km * PER_KM;
            return raining ? pay + 3000 : pay;   // rain bonus: riders only
        }
    }

    // ---------- KISS and YAGNI ----------
    // No RuleEngine with a map of lambdas, and no CurrencyPlugins: the app sells in rupees only.
    // A plain method is enough until a real requirement says otherwise.

    static String rupees(long paise) {
        return "Rs " + paise / 100 + "." + String.format("%02d", paise % 100);
    }

    public static void main(String[] args) {
        long items = 45000;   // Rs 450
        int km = 3;

        System.out.println("-- before: copied rule --");
        System.out.println("charged: " + rupees(new CopyPasteCheckout().total(items, km)));
        System.out.println(new CopyPasteReceipt().line(items, km) + "   <- disagrees with checkout");

        System.out.println("-- after: one DeliveryFee --");
        DeliveryFee fee = new DeliveryFee();
        Checkout checkout = new Checkout(fee);
        ReceiptMailer mailer = new ReceiptMailer(fee);
        System.out.println("charged: " + rupees(checkout.total(items, km)));
        System.out.println(mailer.line(items, km));

        System.out.println("-- rider payout stays separate --");
        RiderPayout payout = new RiderPayout();
        for (boolean rain : List.of(false, true)) {
            System.out.println("rain=" + rain + " pay: " + rupees(payout.forTrip(km, rain)));
        }
    }
}

Notes

The problem

Here is the pain. The delivery fee is forty rupees plus eight per kilometre, and it is free above five hundred. Checkout computes it. The receipt email computes it again, with a copy of the same lines. Months later the business lowers the free delivery limit to four hundred. Someone updates Checkout and forgets the mailer. Now customers pay zero but their receipt shows a fee. That is the bug DRY prevents.

Copy-paste fee rule
// in Checkout
long fee = 4000 + km * 800;
if (total >= 50000) fee = 0;

// in ReceiptMailer, copied
long fee = 4000 + km * 800;
if (total >= 50000) fee = 0;

// later: free delivery now
// starts at 400, Checkout only

DRY

DRY means every piece of knowledge has one clear home. Notice the word knowledge, not code. The fee rule is one business fact, so it lives in one class, DeliveryFee. Checkout and the receipt mailer both ask it. When the free delivery limit changes, you edit one line, and both places are correct at once. The goal is not fewer lines. The goal is one place to change when a fact changes.

DRY in code

In code it is small. A DeliveryFee class holds the base charge, the rate per kilometre and the free delivery limit as named constants, and one method that applies the rule. Money is kept in paise as a long, so there are no rounding surprises. Both callers pass the order total and the distance. Nobody else knows the formula, so nobody else can get it wrong.

One home for the rule
final class DeliveryFee {
    static final long BASE = 4000;
    static final long PER_KM = 800;
    static final long FREE_FROM = 40000;

    long forOrder(long total, int km) {
        if (total >= FREE_FROM) return 0;
        return BASE + km * PER_KM;
    }
}

DRY gone wrong

Now the trap. The rider is also paid eight rupees per kilometre. Same number, same multiplication. A keen developer merges them into one shared method. But these are two different facts. The customer price is set by marketing. The rider rate is set by operations and labour rules. Next month one changes and the other must not. Code that only looks the same by coincidence is accidental duplication. Leave it duplicated.

The wrong abstraction

If you merge anyway, this is what happens. A night surcharge applies only to customers, so you add a flag. A rain bonus applies only to riders, another flag. Soon the shared helper has four booleans and a tangle of ifs, and every change risks breaking a caller you did not think about. This is the wrong abstraction. The fix is to inline it back into two simple methods and let each one evolve on its own.

A helper with flags
long perKm(int km, boolean rider,
           boolean night, boolean rain,
           boolean customer) {
    long r = rider ? 800 : 800;
    if (night && !rider) r += 200;
    if (rain && rider) r += 300;
    ...
}

every caller now depends on
every other caller

A safe test

So how do you decide? Ask one question. If this rule changes, must the other copy change too, every single time? If yes, it is one fact, so merge it. If no, they are separate facts that happen to match today. If you are not sure, wait until you see the same thing a third time. Merging later is cheap. Pulling apart a shared abstraction that six classes depend on is painful.

Should I merge these?
  • same business fact?
  • yes: merge, one home
  • no: keep them apart
  • not sure yet?
  • wait for the third copy
  • (rule of three)
  • merging later is cheap,
  • un-merging is painful

KISS

Next, KISS. Keep it simple. Choose the plainest design that solves the real problem. Here someone replaced the three line fee method with a generic rule engine that reads conditions from a map of lambdas and evaluates them in priority order. It is clever and it can express anything. But a new teammate needs an hour to find out what the fee is, and a bug in the engine breaks every price at once.

KISS in practice

Simple does not mean the fewest characters. A dense one-line stream that nobody can debug is not simple. Simple means a reader understands it quickly and can change it safely. Warning signs: you need a diagram to explain a small rule, a generic framework has exactly one user, or reuse is done through deep inheritance. Plain names, plain if statements and small methods usually win.

Signs of not simple
  • you need a diagram to explain
  • a three-line rule
  • generic engine, one user
  • clever one-liners and
  • streams nobody can debug
  • deep inheritance for reuse
  • simple is not "short":
  • clear names and plain ifs
  • usually win

YAGNI

Third, YAGNI. You are not going to need it. The app only sells in India, in rupees. A developer builds a currency plugin system with exchange rate providers, just in case we go global. Today that code earns nothing, yet it must be read, tested and kept working through every change. And when the company really expands, the real needs are usually different from the guess. Build it when the requirement arrives.

YAGNI is not careless

YAGNI is not an excuse for messy code. It says skip features built for a maybe: extra plugins, extra settings, extra flags. It does not say skip clean structure. Small classes, clear names, tests and one home per rule are what make the future change cheap when it comes. A small interface you already need for testing is fine. A whole framework for a guess is not.

YAGNI vs good design
  • skip: features for a maybe
  • (plugins, configs, flags)
  • keep: things that make any
  • change cheap
  • clear names, small classes,
  • tests, one home per rule
  • cheap seams are fine:
  • an interface you already
  • need for testing

Run it

Watch the clean version run. An order of four hundred and fifty rupees, three kilometres away. Checkout asks DeliveryFee and gets zero, because the free limit is now four hundred. The receipt mailer asks the same class with the same inputs and also gets zero. The two can never disagree, because there is only one copy of the rule. The rider payout stays in its own class with its own rate.

Balancing the three

These rules pull against each other. DRY pushes you to extract shared code. KISS and YAGNI push you to keep things plain and skip extra layers. The tie breaker is the cost of the next change. Extracting a real shared business fact makes changes cheaper, so DRY wins. Extracting a coincidence or building for a guess makes changes more expensive, so simplicity wins.

Balancing the three
  • DRY pushes you to extract
  • KISS and YAGNI push you to
  • keep things plain
  • extract a real shared fact:
  • DRY wins
  • extract a guess or a
  • coincidence: KISS wins
  • judge by cost of change

In interviews

In a machine coding round, use these rules while you design, not as a speech at the end. Say pricing lives in one class, so the fee rule is not copied into checkout and receipts. Say you are not adding multiple currencies now, but the pricing interface leaves room for it. Interviewers like candidates who scope down on purpose. The common mistake is abstracting every two similar lines and ending up with a maze.

Say it like this
  • "Pricing lives in one
  • PricingStrategy, so fee
  • rules are not copied into
  • checkout and receipts."
  • "I am not adding multi-
  • currency now; the interface
  • leaves room for it later."
  • mistake: abstracting every
  • pair of similar lines

Interview questions

What does DRY actually mean?

Every piece of knowledge, such as a business rule or a constant, should have one authoritative place in the code. It is about knowledge, not identical text: two identical lines that represent different facts are not a DRY violation.

What is accidental duplication?

Code that looks the same today but represents different facts with different reasons to change, like a customer delivery rate and a rider pay rate that both happen to be eight per kilometre. Merging them couples two unrelated rules, so the next change to one breaks the other.

What is the wrong abstraction and how do you fix it?

A shared method or class that covers several cases which have drifted apart, usually visible as boolean flags and branches for each caller. The fix is to inline it back into each caller, delete what each does not need, and only extract again if a true shared rule appears.

What is the rule of three?

A guideline to tolerate duplication the first and second time and extract a shared abstraction only when the same thing appears a third time. By then you can see what is truly common, so the abstraction is more likely to be right.

Does KISS mean writing the shortest code?

No. Simple means easy to understand and safe to change. A dense one-liner or a generic engine can be short or powerful yet hard to read and debug. Clear names, small methods and plain control flow are usually simpler.

Is YAGNI an excuse to skip design?

No. YAGNI tells you not to build speculative features, options or extension points nobody needs yet. It still expects clean, tested, well-structured code, because that is what makes adding the real feature cheap later.

How do DRY and YAGNI conflict?

DRY encourages extracting shared abstractions, while YAGNI and KISS discourage adding layers before they pay off. Extract when it removes a real duplicated fact; avoid it when it only removes a coincidence or prepares for a guessed requirement.

How would you apply these principles in a machine coding round?

Keep each rule, such as pricing or validation, in one class that every flow calls, keep the design plain, and state out loud which features you are deliberately leaving out while showing where they would plug in. That shows judgement without over-engineering.