CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 1 min read

The two measures

Hold together inside, loosely tied outside.

Think of a kitchen. Everything for baking sits in one drawer: whisk, scale, tin. That drawer is cohesive. Now imagine every drawer needs a key from the next one before it opens. That kitchen is tightly coupled, and nothing can be moved without breaking the chain.

Cohesion measures how strongly the parts inside one module belong together. FSA puts it this way: a cohesive module is one whose parts should be packaged together, because splitting them would only force the pieces to call each other. High cohesion is the goal.

Coupling measures how much one module needs to know about, or depend on, other modules. HF warns that when a lot of classes depend on each other, a change in one place spreads to the others, and the system becomes costly to maintain and hard to understand. Low coupling is the goal.

So the aim is high cohesion inside classes and low coupling between them. These two are linked. When related code is scattered, classes must call each other a lot, which raises coupling. When unrelated code is lumped together, a class has several reasons to change, which lowers cohesion.

Cohesion

Cohesion is how closely the fields and methods of one class belong together.

Example: a Stack class where nearly every method uses both the list and the counter.

Coupling

Coupling is how much one class depends on the details of another.

Example: a class that must know that a customer holds an address that holds a city.

Check yourself: 1. Which should be high, and which low? 2. How can scattered related code raise coupling? 3. In the kitchen picture, which drawer is cohesive?