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

Coupling and Cohesion in OOP: Law of Demeter with Java Code

Why good classes know little about each other and keep related things together: the kinds of coupling from loose to tight, the Law of Demeter and tell-don't-ask, high and low cohesion, and a practical test for both: look at what changes together. Shown on a ride-hailing app in Java.

  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 / 14

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

Java example

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

/**
 * Coupling and cohesion in a ride-hailing app.
 * Money is in paise (1 rupee = 100 paise).
 */
public class CouplingCohesionDemo {

    // ---------- Before: TripService reaches through Rider into Wallet ----------

    static final class LeakyWallet {
        private long balance;

        LeakyWallet(long balance) {
            this.balance = balance;
        }

        long getBalance() {
            return balance;
        }

        void setBalance(long balance) {
            this.balance = balance;
        }
    }

    static final class LeakyRider {
        private final LeakyWallet wallet;

        LeakyRider(LeakyWallet wallet) {
            this.wallet = wallet;
        }

        LeakyWallet getWallet() {
            return wallet;
        }
    }

    static final class LeakyTripService {
        void endTrip(LeakyRider rider, long fare) {
            // Breaks the Law of Demeter: knows how Wallet stores money.
            LeakyWallet w = rider.getWallet();
            if (w.getBalance() < fare) {
                throw new IllegalStateException("not enough balance");
            }
            w.setBalance(w.getBalance() - fare);
        }
    }

    // ---------- After: tell, don't ask; each class has one job ----------

    static final class Wallet {
        private long balance;

        Wallet(long balance) {
            this.balance = balance;
        }

        /** The balance rule lives with the balance (high cohesion). */
        void debit(long amount) {
            if (amount > balance) {
                throw new IllegalStateException("not enough balance");
            }
            balance -= amount;
        }

        long balance() {
            return balance;
        }
    }

    static final class Rider {
        private final String name;
        private final Wallet wallet;

        Rider(String name, Wallet wallet) {
            this.name = name;
            this.wallet = wallet;
        }

        void pay(long fare) {
            wallet.debit(fare);
        }

        String name() {
            return name;
        }

        long balance() {
            return wallet.balance();
        }
    }

    /** Pricing only. Takes plain numbers: data coupling. */
    static final class FareCalculator {
        private static final long BASE = 5000;
        private static final long PER_KM = 1500;
        private static final long PER_MIN = 320;

        long fare(int km, int minutes) {
            return BASE + km * PER_KM + minutes * PER_MIN;
        }
    }

    /** Messaging only. A real one would call an SMS gateway. */
    static final class TripNotifier {
        void tripEnded(String riderName, long fare) {
            System.out.println("SMS to " + riderName + ": trip ended, paid Rs " + fare / 100);
        }
    }

    static final class TripService {
        private final FareCalculator fares;
        private final TripNotifier notifier;

        TripService(FareCalculator fares, TripNotifier notifier) {
            this.fares = fares;
            this.notifier = notifier;
        }

        void endTrip(Rider rider, int km, int minutes) {
            long fare = fares.fare(km, minutes);
            rider.pay(fare);                       // talk to a direct friend only
            notifier.tripEnded(rider.name(), fare);
        }
    }

    public static void main(String[] args) {
        LeakyRider leaky = new LeakyRider(new LeakyWallet(50000));
        new LeakyTripService().endTrip(leaky, 31000);
        System.out.println("before: balance left " + leaky.getWallet().getBalance());

        Rider asha = new Rider("Asha", new Wallet(50000));
        TripService trips = new TripService(new FareCalculator(), new TripNotifier());
        trips.endTrip(asha, 12, 25);
        System.out.println("after: balance left " + asha.balance());

        try {
            trips.endTrip(asha, 20, 40);
        } catch (IllegalStateException e) {
            System.out.println("second trip refused: " + e.getMessage());
        }
    }
}

Notes

The problem

Here is the problem. When a trip ends, TripService takes the rider, gets the wallet out of it, reads the balance, checks it, and writes a new balance back. It works. But TripService now knows that a rider has a wallet, and exactly how a wallet keeps its money. If wallets gain a credit limit, or riders get a second payment method, TripService has to change too, even though trips did not change at all.

A train wreck call
void endTrip(Rider r, long fare) {
  Wallet w = r.getWallet();
  if (w.getBalance() < fare)
    throw new IllegalStateException();
  w.setBalance(w.getBalance() - fare);
}

TripService now knows Rider
has a Wallet, and how a
Wallet stores money

Two ideas

Two ideas, in plain words. Coupling is how much one class depends on and knows about another. You want it low, which people call loose coupling. Cohesion is how strongly the parts inside one class belong together. You want it high. Low coupling means a change stays inside one class. High cohesion means that class is the obvious place to make it. Good design aims for both at the same time.

Definitions
  • coupling: how much one class
  • depends on and knows about
  • another
  • aim: LOW (loose)
  • cohesion: how closely the
  • parts inside one class
  • belong together
  • aim: HIGH

Kinds of coupling

Coupling comes in kinds, from loose to tight. Data coupling passes only the values needed, like kilometres and minutes. Stamp coupling passes a whole object but uses one field. Control coupling passes a flag that tells the other method which branch to run. Global coupling shares a static variable anyone can change, like this GlobalSurge field. Content coupling, the worst, reaches into another class's internals. Push your code toward the top of the list.

Loose to tight
  • data: pass only the values
  • you need (km, minutes)
  • stamp: pass a whole object
  • but use one field
  • control: pass a flag that
  • says what to do inside
  • global: share a static
  • mutable variable
  • content: reach into another
  • class's internals

Control coupling

Control coupling is very common. A fare method takes a boolean called pool, and the caller passes true or false to choose the branch inside. Now the caller must know how the method is built. Better to give each behaviour its own named method, solo fare and pool fare, or, if the kinds keep growing, one small FareRule interface with a class per kind. Each change then stays in one place.

Flag argument
// caller decides the branch
long fare(int km, boolean pool)

// better: name each behaviour
long soloFare(int km)
long poolFare(int km)

// or one interface per kind:
interface FareRule {
  long fare(int km, int min); }

Law of Demeter

The Law of Demeter gives a simple rule. A method should only talk to its direct friends: its own object, its fields, its parameters and objects it creates. Not to the friends of its friends. So TripService may talk to the rider, but should not reach through the rider to its wallet. A chain like get wallet, then get balance, then set balance, is the warning sign. Fluent builders and streams are fine, since they return the same kind of thing.

Only talk to
  • • this object itself
  • • objects passed in as
  • parameters
  • • objects it creates
  • • its own fields
  • not: a.getB().getC().do()
  • one dot is a hint,
  • not a strict law

Tell, don't ask

The fix is tell, don't ask. TripService tells the rider to pay the fare. The rider passes it to its wallet. The wallet owns the rule about enough balance, because it owns the balance. Now TripService knows one thing, that riders can pay. Add a credit limit, or a second card, and only Rider or Wallet change. The behaviour moved to the class that owns the data, which also raised cohesion.

Tell, don't ask
// TripService
rider.pay(fare);

// Rider
void pay(long fare) { wallet.debit(fare); }

// Wallet owns its rule
void debit(long amount) {
  if (amount > balance) throw ...;
  balance -= amount;
}

Low cohesion

Now cohesion. Look at RideUtils. It calculates fares, sends text messages, builds invoice PDFs and measures map distance. These methods share nothing: no common fields, no common reason to exist. That is low cohesion. The pricing team, the messaging team and the maps team all edit the same file, and every change risks breaking a stranger's code. Names like Utils, Helper or Manager are often a sign of this.

RideUtils
class RideUtils {
  long fare(int km, int min)
  void sendSms(String phone, ...)
  byte[] invoicePdf(Trip t)
  double distance(LatLng a, ...)
}

pricing, messaging, documents
and maps in one class

High cohesion

Split it by job. FareCalculator holds the base fare and the rates and does only pricing. TripNotifier knows how to message a rider and nothing else. Invoices and maps get their own classes too. Each class is now small, has one topic, and its methods use the same fields. That is high cohesion. Notice that TripService now depends on narrow, focused classes, so coupling went down as well. The two ideas usually improve together.

What changes together

Here is a practical way to measure both. Write down the changes you expect, like a new fare rule, a new text message provider, or a credit limit on wallets. For each one, count the classes you would have to edit. One class is great. Many classes means things that change together have been spread apart, which is high coupling. One class that changes for many unrelated reasons means low cohesion. Keep together what changes together.

A practical test
  • list the likely changes:
  • new fare rule
  • new SMS provider
  • wallet credit limit
  • for each, count the classes
  • you must edit
  • one class: good
  • many classes: coupling
  • one class, many topics: low
  • cohesion

Run it

Watch the clean flow. TripService asks FareCalculator for the fare of a twelve kilometre, twenty five minute ride, passing only those two numbers, which is data coupling. It tells the rider to pay. The rider tells its wallet to debit. Then TripService asks TripNotifier to send the receipt message. Each class does one job and only knows the class next to it.

Not zero coupling

A word of balance. Zero coupling is not the goal, because a program is classes working together. The goal is to depend on things that rarely change: small interfaces, simple values and the standard library. And splitting too far hurts as well. Twenty classes with one method each spread one idea across many files, which is its own kind of coupling. Aim for one clear topic per class.

Trade-offs
  • zero coupling = nothing
  • talks to anything
  • aim to depend on things
  • that rarely change:
  • small interfaces, values,
  • the standard library
  • too many tiny classes also
  • hurt: keep a clear topic
  • per class, not one method

In interviews

In design interviews, these words help you justify where each method lives. In a parking lot, say the spot owns the fits method because the spot owns its size, which is high cohesion. Say the lot depends on a pricing interface, not a concrete class, which is loose coupling. Common mistakes are one giant manager class that does everything, long getter chains, and boolean flags that pick behaviour.

Say it like this
  • "Spot owns fits(), because
  • Spot owns its size."
  • "The lot depends on a
  • PricingStrategy interface,
  • not on HourlyPricing."
  • mistakes: god classes like
  • ParkingManager, getter
  • chains, boolean flags

Interview questions

What is the difference between coupling and cohesion?

Coupling measures how much one class depends on and knows about other classes; cohesion measures how closely the members inside one class belong together. Good designs have low coupling and high cohesion, so a change touches few classes and lands in an obvious place.

Name some types of coupling from loosest to tightest.

Data coupling (passing only needed values), stamp coupling (passing a whole object but using part of it), control coupling (passing a flag that selects behaviour), common or global coupling (shared mutable global state), and content coupling (reaching into another class's internals).

What is the Law of Demeter?

A method should only call methods on itself, its fields, its parameters and objects it creates, not on objects returned by those. Chains like a.getB().getC().doIt() break it because the caller now depends on the internal structure of several classes.

What does tell, don't ask mean?

Instead of pulling data out of an object and deciding for it, tell the object to do the work. For example rider.pay(fare) instead of reading and writing the wallet balance from outside. The rule then lives with the data it uses.

How can you spot low cohesion?

Methods that do not share fields, a class that changes for many unrelated reasons, and vague names like Utils, Helper or Manager. Splitting such a class by topic usually makes each part easier to test and change.

How do you measure coupling and cohesion in practice?

List the changes you expect and count the classes each one touches. If one change edits many classes, related logic is scattered and coupling is high; if one class changes for many unrelated reasons, its cohesion is low. Metrics tools exist, but this test is what matters in design.

Why are boolean flag parameters considered a design smell?

They are control coupling: the caller must know about the branches inside the method, and the method does two jobs. Separate named methods or a small interface with one implementation per behaviour keep each change local.

How do interfaces reduce coupling?

A class that depends on a small interface only knows the method contract, not the concrete class behind it. Implementations can then change or be swapped, for example in tests, without editing the caller.