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.
Take home message
A class should do the smallest possible useful thing.
Example Design¶
The examples are (partial) designs for the CourseReVU App.
The Course
class below, arguably has too many responsibilities. It would have to change if we change, e.g. the format of the reviews or ratings.
On the other hand, separating Review
and Rating
may be an overkill, since ratings are just integers (0 to 5) they may very well be integrated into (and seen as part of) Review
. So, the design below is trying too much to increase cohesion.