Cohesion and Coupling in Java: Free Java tutorials

Cohesion and Coupling are two of the most important Object-Oriented Programming concepts apart from Inheritance, Polymorphism, and Encapsulation. We will discuss and understand cohesion and coupling in this tutorial.

Coupling in Java

The degree of dependency between the components is called coupling. If the dependency is more, then it is considered as tight coupling. And if the dependency is less, then it is called loose coupling.

// class X
class X
{
	// Accessing x from class Y's static variable
	static int x = Y.y;
}

//class Y
class Y
{
	// Accessing y from class Z's static variable
	static int y = Z.z;
}

//class Z
class Z
{
	// Accessing z from class W's static method
	static int z = W.getNumber();
}

//class W
class W
{
	// static method of class W which will return the number
	public static int getNumber()
	{
		return 5;
	}
}

// Main class
public class Demo 
{
	public static void main(String[] args)
	{
		// printing static variable x of class X
		System.out.println(X.x);	
	}
}

Output:

5

The above components are said to be tightly coupled with each other because dependency between the components is more.

Tightly coupling is not a good programming practice. Because it has following several serious disadvantages:

  1. Without affecting remaining components, we cannot modify any component. Hence, enhancement becomes difficult.
  2. It suppresses reusability because of too much of dependency.
  3. It reduces maintainability of the application.

Hence, we have to maintain dependency between the components as less as possible. So, loosely coupling is a good programming practice.

Cohesion in Java

For every component, a clear well-defined functionality is defined. Then the component is said to follow high cohesion.

Low cohesion is not recommended because of the same disadvantages as discussed above of high coupling.

High cohesion is always a good programming practice because it has following several advantages:

  1. Without affecting any components, we can modify any component. Hence, enhancement becomes easy.
  2. It promotes reusability of the code.
  3. It improves maintainability of the application.

For example, Gmail is the best example of high cohesion. It has an independent implementation for each individual functionality/feature.

Like, for login, it may have login.java file. After that, it may have separate individual components for validation, view inbox, reply to mail and other features of Gmail.

This type of high cohesion makes it very easy to maintain and enhance the application.

Note – High cohesion and low coupling are the best programming practice and we must try to follow that.

This is all about Cohesion and Coupling in Java. Hope you find this tutorial helpful.

Leave a Comment

Your email address will not be published. Required fields are marked *