Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / SOLID Principles

    The Friends: DRY, KISS, YAGNI, Law of Demeter

    Taught step by step, with real output.

    Chapter 7 of 82 min read

    PrincipleMeansStudyBuddy exampleCaution
    DRY — Don't Repeat Yourselfeach piece of knowledge lives in one placethe pass mark 150 is a constant used everywhere, not typed in 12 placestwo pieces of code that look alike but change for different reasons aren't duplication — merging them couples them
    KISS — Keep It Simplethe simplest design that worksa List of rules, not a plugin framework with configuration files"simple" ≠ "easy to write once"; it means easy to read and change
    YAGNI — You Aren't Gonna Need Itdon't build for imagined future needsno multi-currency billing until someone actually asksbalances OCP: add extension points when change is real
    Law of Demeter — "talk to friends, not strangers"a method uses its own fields, parameters and objects it creates — not long chains through themstudent.canAfford(5) instead of student.getAccount().getWallet().getCredits() >= 5long "train wreck" chains couple you to every class along the chain

    Check yourself

    3 questions
    1

    What's the difference between DRY and "never write similar code twice"?

    Show answer

    DRY is about one source of truth for each piece of knowledge; similar-looking code that changes for different reasons should stay separate.

    2

    How do YAGNI and OCP balance each other?

    Show answer

    OCP says make likely changes cheap; YAGNI says don't build for changes that aren't real. Add extension points where change has happened or clearly will.

    3

    What's wrong with a.getB().getC().getD().doThing()?

    Show answer

    It couples your code to the internal structure of B, C and D (Law of Demeter); a change in any of them breaks you. Ask a to do the thing.