Software

Coupling and Cohesion

Coupling and cohesion are metrics to evaluate design complexity.

These metrics helps to achieve a more manageable system.

Coupling

Coupling focuses on complexity between a module and other modules. If your module is highly reliant on other modules, then this module is tightly coupled to others (puzzle). If your module finds it easy to connect to other modules, this module is loosely coupled to others (Lego).

Coupling.png
Coupling

When evaluating the coupling of a module, you need to consider degree, ease and flexibility.

  • Degree is the number of connections between the module and others. With coupling the degree should be small. For example if the module needed to connect to other modules through a few parameters or narrow interfaces, then the degree would be small, hence coupling loose.
  • Ease is how obvious are the connections between the module and others. You should care about how easy to make connections without needing to understand the implementations of the other modules.
  • Flexibility is how interchangeable the other modules are for this module. You should think about how other modules can be easily replaceable for something better in the future.

Cohesion

Cohesion focuses on complexity within a module. It represents the clarity of the responsibilities of a module.

Module -> Classes and Methods.

Cohesion.png
Cohesion

Low cohesion is when a module tries to encapsulate more than 1 purpose or has unclear purpose. If the module has more than 1 responsibility it’s probably time to split the module.

Bad Cohesion.png
Low cohesion.
// Low cohesion example, depends on the flag, it can return different type of values which is not good
public void Get(int controlFlag){
    switch(controlFlag){
        case 0:
            return this.humidity;
            break;
        case 1:
            return this.temperature;
            break;
        default:
            throw new UnknownControlFlagException();
    }
}

High cohesion is when a module performs one task and nothing else or has clear purpose.

Good Cohesion.png
High cohesion.
// High cohesion example

public interface ISensor {
    Get();
}

public class HumiditySensor: ISensor {
    public Get(){
        // implementation
        return this.humidity;
    }
}

public class TemperatureSensor: ISensor {
    public Get(){
        // implementation
        return this.temperature;
    }
}
Good design is low coupling and high cohesion.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.