← Back to Week 5

Cohesion

How related are the things inside a single class? Aim for high cohesion — every field and method in a class should serve the same purpose.

Low cohesion do less of this
class Employee {
name;
payRate;
hoursWorked;
favoriteRestaurant;
currentMovie;
getTotalPay()
recommendDinner()
printWeatherForecast()
}
Some members deal with payroll. Others deal with dinner recommendations. Others print the weather. None of them belong together — this class is a kitchen sink.
High cohesion do this
class Employee {
}
Every member is about this employee's payroll. They all naturally belong together. The class has one job, and is good at it.
How to spot a cohesion problem
Could you describe the class in one short sentence?  A class with high cohesion has a one-line description ("manages an employee's payroll info"). If yours needs the word "and" three times, cohesion is leaking.
If you removed a method, would the class still make sense?  If the answer feels like "yes, easily," that method probably doesn't belong here.
Do all the fields get used by all the methods?  Total overlap isn't required, but if half the fields are completely unused by half the methods, you might be looking at two classes pretending to be one.
Cohesion is about within: how related are the parts inside one class? The partner concept — coupling — is about between: how dependent are classes on each other? We'll cover coupling later this week when we build the card game (Module 5). For now, the goal is just one focused class at a time.
← Default Access Modifier The Testing Pyramid →