High Cohesion GRASP Pattern

High cohesion is an evaluative pattern that attempts to keep objects appropriately focused, manageable and understandable. High cohesion is generally used in support of low coupling.
The term cohesion is used to indicate the degree to which a class has a single, well-focused responsibility. Cohesion is a measure of how the methods of a class or a module are meaningfully and strongly related and how focused they are in providing a well-defined purpose to the system.

Problem

How to keep classes focused, understandable and manageable?

Solution

Assign responsibilities so that cohesion remains high. Try to avoid classes to do too much different things.

Key points about high cohesion

  • The code has to be very specific in its operations.
  • The responsibilities/methods are highly related to the lass/module.
  • The term cohesion is used to indicate the degree to which a class has a single, well-focused responsibility. Cohesion is a measure of how the methods of a class or a module are meaningfully and strongly related and how focused they are in providing a well-defined purpose to the system. The more focused a class is the higher its cohesiveness - a good thing.
  • A class is identified as a low cohesive class when it contains many unrelated functions within it. And that what we need to avoid because big classes with unrelated functions hamper their maintaining. Always make your class small and with a precise purpose and highly related functions.

Example

In this example, the purpose of MyReader class is to read the resource and it does that only. It does not implement other unrelated things. Hence it is highly cohesive.
class HighCohesive {
    // -------------- functions related to read resource
    // read the resource from disk
    public String readFromDisk(String fileName) {
         return "reading data of " + fileName;
    }

    // read the resource from web
    public String readFromWeb(String url) {
         return "reading data of " + url;
    }

    // read the resource from network
    public String readFromNetwork(String networkAddress) {
         return "reading data of " + networkAddress;
    }
}

Reference


Comments