Cohesion
Posted On April 22, 2022

Understanding Cohesion
Imagine you have a toolbox. In a highly cohesive toolbox, all tools are related to a specific type of task, e.g., a set of screwdrivers of various sizes. In a low cohesive toolbox, you might have a screwdriver, a garden spade, some cooking spices, and a light bulb – essentially a mix of unrelated items.
Similarly, in software:
- A highly cohesive class or module would have functions/methods that are closely related in functionality. For instance, a
FileHandlerclass might have methods likeread(),write(),close(), etc., because all these methods deal with file operations. - A low cohesive class or module might have a wide range of unrelated responsibilities. For example, a class named
UserOperationsthat manages user data, sends emails, and also handles file storage would be considered to have low cohesion because it is trying to manage too many unrelated tasks.
Why is Cohesion Important?
- Maintainability: Highly cohesive classes/modules are generally easier to maintain. Since all the functionality is closely related, a developer can make changes without having to jump between multiple unrelated classes or modules.
- Reusability: A class or module with a single, well-defined responsibility is more likely to be reused in different parts of a software application or even in different projects.
- Reduced Side Effects: Changes in a highly cohesive class/module are less likely to have unintended side effects on unrelated functionality, because that unrelated functionality simply shouldn’t be in the class/module in the first place.
- Clarity and Understandability: It’s easier to understand the purpose and functionality of a class or module when it has a clear and singular responsibility. This clarity aids both in the initial development and later during code reviews or onboarding of new team members.
Levels of Cohesion
There are several recognized levels of cohesion, ranging from worst to best, including:
- Coincidental Cohesion: No meaningful relationship among the elements of a module.
- Logical Cohesion: Elements perform similar activities, selected with ‘if’ statements.
- Temporal Cohesion: Elements involved in activities related in time (e.g., initialization).
- Procedural Cohesion: Elements involved in different parts of a sequence of activities.
- Communication Cohesion: Elements operate on the same data (or record).
- Sequential Cohesion: Output from one element serves as input to another.
- Functional Cohesion: All elements contribute to a single activity or task.
The aim, in good software design, is to achieve functional cohesion, where each module or class has a single, well-defined responsibility. However, it’s also essential to strike a balance, ensuring that classes or modules don’t become too granular or too overloaded.