High Cohesion
Principle
Ensure that each class is highly cohesive.
Object-Oriented designers use the word cohesion to describe everything in a class is related to its central purpose. It is a measure for how well the internal parts of a class (e.g. the methods and attributes) belong together.
A highly cohesive class is one that only comprise responsibilities which belong together. A class ideally has a single responsibility.
Why does this matter?
- Applications that are easy to change consist of classes that are easy to reuse.
- A class that has many responsibilities is difficult to reuse.
- A class that has several responsibilities, has many reasons to change. When it changes,
- it may change for a reason that is unrelated to your use of it.
- there's a possibility of breaking every class that depends on it.
How to figure out if a class is not cohesive?
- Here is one strategy: describe your class in one sentence.
- if you cannot, it probably has too many responsibilities.
- if your description has "and"/"or" in it, it probably has too many responsibilities.
For example, consider the Employee
class below, that arguably has too many responsibilities. It represents an employee and prints time sheet. We would have to change it if we change the format of the timesheet report.
We can solve this by moving the behavior related to printTimeSheet
into a separate class.
Take home message
A class should do the smallest possible useful thing.