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.
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.
- 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.
- 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.
// 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.
- • 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.
// 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.
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.
- 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.
- 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.
- "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