Cohesion And Coupling Uncovered -Java
Tags: cohesive, coupling, java, advanced
Published: 2022-09-16 18:29:43

The secret of creating manageable code is adhering to “**high cohesion and low coupling**”.
<br>
--
### But what does these terms actually mean?
**Cohesion and coupling** generally focus on association or dependency between modules. In object-oriented programming languages like java, classes represent modules.

<br>
--
**COHESION**

Cohesion is the principle which makes sure that a single class is designed with a well-focused purpose. It can also be referred as the degree of atomicity of the concerned code base.

In simple terms, cohesion means focusing on one task at a time. There may be multiple tasks to be done by a team, the team lead allocates each task to a single member, here each member represents a module/class, and their focus is on a particular task only.
<br>
--

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9ceiqniqyecdolwg9nc.gif)
<br>
--

The advantage of high cohesion is that the code is **easier to maintain and highly reusable** as the classes have a well-focused approach.
<br>
--
- Suppose we have a class that adds two numbers, also the same class displays the result. This is an example of a low cohesive class because displaying the result and the addition operation don’t have much in common.

- To make it high cohesive, we would have to create a class Display and a class Addition. The Display will call the add method of the Addition class to get the result and display it. This way to develop a high cohesive solution.

<br>
--
**Code**:

```
//Separate classes for addition and display operations — High cohesion
class Addition {

int a = 5;
int b = 5;

 public int add(int a, int b) {
 this.a = a;
this.b = b;
return a + b;
}

}
class Display {

public static void main(String[] args) {
Addition obj = new Addition ();
System.out.println(obj.add(5, 5));
}

}
```
<br>
--
**Pictorial Representation**
<br>
--

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqg6rx49byqpl9cikg86.png)



<br>
--
**COUPLING**

On the other hand, Coupling refers to how strongly a module is connected to other modules. In other words, it is the number of connections between two or more units. There are two types of coupling, **Tight coupling and loose coupling.**
<br>
--
**Code:**

```
//Two classes with strong inter-dependency — High coupling
class Volume {
public static void main(String args[]) {

Box b = new Box(5,5,5);
System.out.println(b.volume);
}
}

class Box {

public int volume;

Box(int length, int width, int height) {
this.volume = length * width * height;
}
}
```
<br>
--
**Explanation:** In the above example, there is a strong inter-dependency between both the classes. If there is any change in Box class, then it will be reflected in the result of Class Volume. Another best example of tight coupling is RMI(Remote Method Invocation).

Therefore, **Increased cohesion and decreased coupling do lead to good software design**. The most effective way to decrease coupling and increase cohesion is **design by interface.**

<br>
--

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cegtrbjy954hj9mpfzuw.gif)
<br>
--

By this method, the major functional objects of the class only know each other through the interface that they implement, thereby reducing coupling to a greater extent also the implementation of an interface as a sequence introduces cohesion.
<br>
--
### Step by Step Approach
Consider the following example, in which we are constructing a typical monitorable **ConnectionPool** and have the following specifications. Be aware that while it may seem excessive for a straightforward class like **ConnectionPool**, the main goal is to illustrate low coupling and strong cohesion with a few simple examples, which I hope will be beneficial.

1. assist in establishing a connection

2. disrupt a connection.

3. view connection and usage statistics

4. get statistics on connection time.

5. Record the connection release and retrieval data in a database for reporting purposes.

We can create a **ConnectionPool** class with low cohesion by cramming all of this functionality and responsibility into a single class as seen below. We can see that this one class is in charge of connection management, communication with the database, and upkeep of connection statistics.

<br>
--

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7baw2lg4talksmm6k5w.png)

<br>
--


**High cohesion** allows us to distribute these responsibilities among classes, improving maintainability and reusability.


<br>
--
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21wmixrsomoqj7ubqonu.png)
<br>
--


We shall use the high cohesion **ConnectionPool** picture above to illustrate low coupling. Despite supporting high cohesion, the **ConnectionPool** is tightly coupled with the **ConnectionStatistics** class and the **PersistentStore** because it directly interacts with them.

Instead, we may create a **ConnectionListener** interface, let these two classes implement it, and allow them to register with the ConnectionPool class in order to reduce coupling. Additionally, the ConnectionPool will loop through these listeners and alert them to connection get and release events, enabling for reduced coupling.
<br>
--
### Why adapting High Cohesion and Low Coupling is good?
The code becomes maintainable which in turn increases the productivity for developers.

Then it becomes easier to design new features and write code. Modular, component-based, and layered code reduces the risks even when changes are made by the developer.

When the code is loosely coupled, that is when the modules are independent of each other, we can write code within one module without impacting other modules.


<br>
--
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n22pvic2jwp0v7r3g3fd.gif)
<br>
--
### To Reader’s Attention
Asking yourself these questions while you write and work with your code base would help.

1. How many modules do I need to modify or add in order to create a new functionality?

2. How many separate locations will this modification occur?

3. How challenging is testing my code?

4. Can we make this better by making the code loosely coupled? Can we make this better by making our code more cohesive?

And yeah, if you have all these questions in your knowledge while coding your application, you can achieve the expected results!

Happy coding!