# Less Coupling High Cohesion

## Coupling

![](/files/-M4CTDtw5w-SRJ6bbq0q)

(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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heronyang.gitbook.io/clean-up-your-spaghetti/3_ideal_coding_process_and_principles/less_coupling_high_cohesion.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
