High Cohesion GRASP Pattern

Read about GRASP Patterns: GRASP Patterns Overview

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 or too different things.

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.

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 precise purpose and highly related functions.

Key points about  high cohesion 

  • The code has to be very specific in its operations. 
  • The responsibilities/methods are highly related to class/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 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;
}
}

Related GRASP Patterns

Comments

Popular posts from this blog

Design Patterns used in Hibernate Framework

Value List Handler