Coupling and cohesion
- Lesson 2 of 32
- 10 min
- Beginner
- 12 steps
You rename one field and four files break in two modules. That pain has a name: high coupling and low cohesion. Here you learn to spot them in code and fix them without burying everything under layers.
- Classes the change touches
- —
- Modules it touches
- —
- Reasons for Utils to change
- —
- request
- response
- failed request
Step 1 of 12
Problem
An invoice that walks through half the system
An online shop has two modules: Orders (Order, Customer, Address) and Billing (Invoice and friends). To work out the tax, Invoice needs the customer's country.
To get it, it writes this.order.customer.address.country: it goes through Order, into Customer and from there into Address. It works, but Invoice has just learned how the Orders module is built on the inside.
Step 2 of 12
Concept
Coupling: how much you need to know about the other side
Coupling measures how much one module has to know about another to work. Invoice does not just know that an order exists: it knows the order has a customer, the customer has an address and the address has a country.
Every thing it knows is a place where someone else's change can break it. The idea is not new: the term was popularised by the paper «Structured Design» by Stevens, Myers and Constantine (IBM Systems Journal, 1974), and Constantine was already working on these ideas in the 1960s.
Step 3 of 12
Problem
You rename a field and four classes break
Someone renames country to countryCode in Address. A small change, in one module. But Invoice, Report (sales by country) and Utils (which takes a whole Customer to work out the rate) also walked the chain down to country.
Result: 4 classes to touch in 2 modules, and two teams to coordinate over a field name.
What changed
- country → countryCode in Address
- Invoice, Report and Utils stop compiling
Step 4 of 12
Solution
Ask for what you need, not the whole object
Order offers a country() method that asks Customer, and only Customer reads Address. Invoice and Report call this.order.country(), and the rate comes from taxRate(country: string): it takes a string, not a Customer.
Now the same rename touches 2 classes (Address and Customer) in 1 module. Whatever sits behind Order can change without Billing noticing.
What changed
- Order.country() and Customer.country()
- taxRate takes a string
- Utils no longer knows Customer
Step 5 of 12
Concept
Cohesion: does what is inside belong together?
Cohesion measures how much the things living in one module have to do with each other. Look at Utils: it formats dates, works out taxes and turns titles into URLs.
Those are 3 reasons to change that have nothing in common: a new date format, a new tax law or a URL rule all make you open the same file, and everyone who imports Utils is tied to all three.
Step 6 of 12
Solution
Group what changes together
Keep in the module only what changes for the same reason. taxRate stays and the module is renamed TaxRates; formatDate moves to Report, which is what uses it, and slugify to the code that builds URLs.
Now a new tax law changes one file, and code that only needs taxes no longer drags dates and URLs along.
What changed
- Utils becomes TaxRates
- formatDate and slugify leave the module
Step 7 of 12
Technique
Real case: depend on an interface
In Java, SLF4J is a logging facade: your code writes against its Logger interface and does not know which library is behind it. According to its documentation, you pick the backend (Logback, Log4j or java.util.logging) at deployment time.
In the diagram, Invoice only sees Logger, the dashed block: an interface. Logback implements it, but Invoice never names it.
Step 8 of 12
Solution
You swap the backend without touching your code
The team decides to move from Logback to Log4j. It changes the dependency that ships with the deployment and that is it: 0 classes of the application change, because none of them named Logback.
Compare with the start of the lesson: there, a rename touched 4 classes. The difference is not the amount of code, it is how much each part knows about the other.
What changed
- Logback → Log4j
- Invoice: 0 lines changed
Step 9 of 12
Problem
Hidden coupling: a module with state
In Node.js, require caches every module: every call that resolves to the same file gets exactly the same object. If that object can be changed, every file that imports it is tied to whatever the others do with it.
Here Report sets currency to "USD" for a report, and Invoice starts billing in dollars. There is no arrow between Report and Invoice, yet they are coupled through config.js.
Step 10 of 12
Trade-off
What they do not mean
Zero coupling does not exist: a program is code talking to other code. The goal is for each module to know the minimum about the others, like Invoice that only knows Order.
Cohesion is not about small files, and not repeating code (DRY) does not always help: if two unrelated features share a helper, any change for one can now break the other.
Step 11 of 12
Trade-off
When it is not worth it
Decoupling adds interfaces, parameters and jumps between files. In a one-off prototype or script, that cost never comes back: write it directly and, if it survives, refactor.
Do not split a module that is already cohesive either: breaking a 200-line module that changes together into 10 files (example sizes) only makes you jump between more tabs, without lowering coupling.
Step 12 of 12
Summary
Summary
Coupling: how much one module knows about another. Every thing it knows is a place where it can break.
Measure a design with one question: if I change this, how many classes and modules do I touch?
Ask for what you need (country(), a string), not the whole object.
Cohesion: group what changes for the same reason and separate what does not.
Depend on interfaces where the other side can change, as with SLF4J, and do not decouple prototypes or split cohesive modules.
← → step · R replay · Space pause
You will learn
- Recognise how much one module knows about another (coupling) (covered)
- Measure a change in the classes and modules it touches (covered)
- Lower coupling by asking only for what you need (covered)
- Group what changes together (cohesion) (covered)
- Depend on an interface, the way SLF4J does (covered)
- Know when decoupling is not worth it (covered)