# Less Coupling High Cohesion

## Coupling

![](https://3086426873-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4CT8WYORuS-KboTDGB%2F-M4CT8x9OG0AAsbaoOFE%2F-M4CTDtw5w-SRJ6bbq0q%2Fcoupling.png?generation=1586142728336307\&alt=media)

(from [Wikipedia](https://en.wikipedia.org/wiki/File:Coupling_sketches_cropped_1.svg#filelinks))

Definition: the degree to which the different modules/classes depend on each other, suggestion is all modules should be independent as far as possible, that's why low coupling. It has to do with the elements among different modules/classes. (from [stackoverflow](http://stackoverflow.com/questions/14000762/what-does-low-in-coupling-and-high-in-cohesion-mean))

* Things that don't depend upon each other should not be artificially coupled.
  * Artificial coupling: a coupling between two modules that serves no direct purpose.

## Cohesion

Definition: the degree to which the elements of a module/class belong together, suggestion is all the related code should be close to each other, so we should strive for high cohesion and bind all related code together as far as possible. It has to do with the elements within the module/class. (from [stackoverflow](http://stackoverflow.com/questions/14000762/what-does-low-in-coupling-and-high-in-cohesion-mean))

Here's a very cohesive class:

```java
public class Stack {

    private int topOfStack = 0;
    List<Integer> elements = new LinkedList<Integer>();

    public int size() {
        return topOfStack;
    }

    public void push(int element) {
        topOfStack ++;
        elements.add(element);
    }

    public int pop() throws PoppedWhenEmpty() {
        if (topOfStack == 0) {
            throw new PoppedWhenEmpty();
        }
        int element = elements.get(--topOfStack);
        elements.remove(topOfStack);
        return element;
    }

}
```

* When classes lose cohesion, split them!
* Code may be longer (but it's fine).

## Further Reading

* [HIGH COHESION, LOOSE COUPLING](http://thebojan.ninja/2015/04/08/high-cohesion-loose-coupling/)
* [Stackoverflow: Cohesion & Coupling](http://stackoverflow.com/questions/3085285/cohesion-coupling)
