Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 57 ยท Design Principles

DRY, KISS, YAGNI, Law of Demeter and Composition over Inheritance

Learn the everyday design rules beyond SOLID: DRY, KISS, YAGNI, the Law of Demeter, tell don't ask, cohesion, coupling and composition over inheritance.

SOLID is not the whole story. Good designers also carry a handful of short rules of thumb that guide thousands of small decisions: should I extract this duplicate? Is this abstraction worth it? Why does this line reach through four objects? This lesson covers the most useful ones: DRY, KISS, YAGNI, the Law of Demeter, tell, don't ask, and composition over inheritance, plus the two ideas that sit under all of them, cohesion and coupling.

None of these rules is a law of nature. They sometimes pull in opposite directions (DRY wants you to merge things, YAGNI wants you to wait), and part of your job is judging which one matters in the situation. Treat them as questions to ask, not commands to obey.

The short rules

DRY One piece of knowledge, one place.
KISS Prefer the simplest thing that works.
YAGNI Do not build it until you need it.
Demeter Talk to friends, not strangers.

Each one is a cheap check you can apply while reading a diff.

1 / 2

Cohesion and coupling

Cohesion measures how strongly the parts of one module belong together. A Money class with add, subtract and format has high cohesion. A Utils class with sendEmail, parseDate and drawCircle has almost none. Coupling measures how much one module must know about another. Low coupling means you can change or replace one module without touching the other.

You want high cohesion and low coupling. They reinforce each other: when a module has one clear purpose, other modules need to know only that purpose. Almost every principle in this lesson is a way to push one of those two dials in the right direction.

DRY: Don't Repeat Yourself

DRY says every piece of knowledge should have a single, authoritative home. The key word is knowledge, not text. Two code blocks that look the same but represent different business rules are not duplication; merging them couples things that will change for different reasons. Two blocks that look different but encode the same rule (the minimum password length, written as 8 in the form check and > 7 in the API) are real duplication, and one of them will eventually be forgotten when the rule changes.

JS Applying DRY to one rule

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A useful guard against over-eager DRY is the rule of three: tolerate a duplicate the first time, notice it the second time, and extract on the third, when you can see what really varies. Extracting too early often creates an abstraction with flags for every case, which is harder to read than the copies were.

KISS: Keep It Simple

KISS says that among designs that solve the problem, the simplest one usually wins. Simple does not mean short or clever; it means a new teammate can read it and predict what it does. A nested ternary chain is short but not simple. Three plain if statements are longer and simpler.

Watch for the urge to show off a pattern. If a function with two branches solves the task, wrapping it in a Strategy, a Factory and a registry is not good design; it is a pattern-hunting trap. Add structure when the code pushes back, not before.

YAGNI: You Aren't Gonna Need It

YAGNI says not to build features or abstractions for needs you only imagine. "We might switch to another database someday" justifies a clean boundary at the data access layer, but it does not justify generic query builders, plugin systems and configuration flags for ten databases you do not use. Speculative code has costs now (reading it, testing it, working around it) and often turns out wrong when the real requirement appears, because you guessed the shape.

YAGNI is not an excuse to write messy code. Keep the code easy to change (small functions, clear names, tests) and defer the feature itself. Those two habits together let you add the abstraction in an afternoon when it is genuinely needed.

Tell, don't ask and the Law of Demeter

The Law of Demeter (also "the principle of least knowledge") says a method should talk only to its immediate friends: itself, its parameters, objects it creates, and its own fields. It should not reach through one object to a second and a third. A line like order.customer.wallet.balance forces the caller to know how orders, customers and wallets are connected. If any link changes, every caller breaks.

Tell, don't ask is the practical companion: instead of fetching an object's data to make a decision for it, tell the object what you want and let it decide.

JS Removing a train wreck

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Now SafeWallet can change how it stores money (cents, a ledger, a remote service) and nobody outside needs to know. The rule has a cost: you write small forwarding methods like pay. Plain data objects (records, DTOs) and fluent builders are fine exceptions, because chaining on them is not reaching through a hidden structure.

Composition over inheritance

Inheritance ties a child to the parent's implementation for life, and the combinations explode. With birds that can fly, swim, or both, inheritance forces you to pick one tree. Composition builds an object from smaller parts that it has, and you swap or combine those parts freely.

JS Combining abilities by composition

Press Run (or Ctrl + Enter) to see the console output here.

No output.

There is no Bird base class that promises flight to a penguin, so there is nothing for Liskov to complain about. In Java or C++ the same idea appears as fields holding strategy objects (FlyBehavior, SwimBehavior) that the class delegates to; this is exactly the Strategy pattern, and you will meet it again soon.

Inheritance is still the right tool when there is a true, stable "is-a" relationship and the subclass honors the parent's whole contract. A good rule: inherit to share a type, compose to share behavior.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does DRY really mean?

    DRY is about duplicated knowledge, not duplicated text. Lookalike code that encodes different rules should stay separate.
  2. 2. Which situation best illustrates a YAGNI violation?

    YAGNI warns against building for imagined future needs, which cost effort now and often guess the wrong shape.
  3. 3. What is wrong with the line order.customer.wallet.balance in calling code?

    This breaks the Law of Demeter: the caller knows how orders, customers and wallets are linked, so any change in that chain breaks it.
  4. 4. When is inheritance a good choice?

    Inheritance suits true subtyping. For reusing behavior, composition is more flexible and avoids contract violations.
  5. 5. What does high cohesion with low coupling give you?

    When modules each have a clear purpose and know little about each other, a change in one rarely ripples into others.

Summary

  • Cohesion (things belong together) and coupling (modules know little of each other) underlie most design advice.
  • DRY removes duplicated knowledge; use the rule of three to avoid premature merging.
  • KISS and YAGNI keep designs small: solve today's problem, keep the code easy to change.
  • The Law of Demeter and "tell, don't ask" stop callers from reaching through object graphs.
  • Prefer composition for sharing behavior; inherit only for a true, stable is-a relationship.
  • These are guidelines that sometimes conflict; judge each case.

Next lesson: Singleton, the first of the creational patterns.