Less Coupling High Cohesion

Coupling

(from Wikipedia)

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)

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

Here's a very cohesive class:

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

Last updated