High Cohesion
Principle
Ensure that each class is highly cohesive.
Object-Oriented designers use the word cohesion to describe everything in a class as related to its central purpose. It is a measure of how well the internal parts of a class (e.g., the methods and attributes) belong together.
Single Responsibility
A highly cohesive class is one that only comprises responsibilities that 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. Moreover, when a class changes, 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, which arguably has too many responsibilities. It represents an employee and prints a timesheet. 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.