Cohesion
In this tutorial, we are going to discuss Cohesion in Java. For every component we have to define a well defined single purpose. Such type of components are said to be followed high “cohesion”.
In object-oriented design, cohesion refers all about how a single class is designed. Cohesion is the Object-Oriented principle most closely associated with ensuring that a class is designed with a single, well-focused purpose.
E.g
Suppose we have a class that multiply two numbers, but the same class creates a pop-up window displaying the result. This is an example of a low cohesive class because the window and the multiplication operation don’t have much in common.
To make it high cohesive, we would have to create a class Display and a class Multiply. The Display will call Multiply’s method to get the result and display it. This way to develop a high cohesive solution.
class Multiply {
int a = 5;
int b = 5;
public int multiply(int a, int b)
{
this.a = a;
this.b = b;
return a * b;
}
}
class Display {
public static void main(String[] args)
{
Multiply m = new Multiply();
System.out.println(m.multiply(5, 5));
}
}
The main advantages of High Cohesion are:
- It improves maintainability.
- Enhancements is easy.
- Promotes reusability.
Note
- High cohesion is when you have a class that does a well-defined job. Low cohesion is when a class does a lot of jobs that don’t have much in common.
- High cohesion gives us better-maintaining facility and Low cohesion results in monolithic classes that are difficult to maintain, understand and reduce re-usability.