Coupling and Cohesion

Coupling

Coupling is the degree of mutual interdependence between separate units of a Program i.e. how components or modules or classes are linked with one another.

When the two classes depends on each other and when it is difficult to change one without changing the other, they are said to be tightly-coupled.

If we can vary one part of the program independently of another, then they are said to be loosely-coupled

Two classes can be linked by

  1. Inheritance
  2. Interface
  3. Generic Interface
  4. Delegates
  5. Anonymous Delegates
  6. Generic Delegates
  7. Object Composition
  8. WCF
  9. Events
  10. Web Services
  11. LINQ – Most Loosely coupled

In Inheritance, changing the Base class affects all the Derived Classes. For example, adding an abstract method in base class breaks all the derived class. It is most tightly coupled.

WCF, Web Services and LINQ are most loosely coupled.

The remaining features lie somewhere between Tight coupling and Loose coupling.

It is advisable to have a loosely coupled design. 

 

Cohesion

Cohesion is the number and diversity of tasks that a single unit is responsible for. It is the degree to which the responsibilities of a Module or component form a meaningful unit.  It is inversely proportional to the number of responsibilities a module has.

If each unit is responsible for one single logical task, it is said to have High cohesion. Cohesion is applicable for both classes and methods.

It is always better to have High cohesion.

The philosophy behind Cohesion is often echoed in different Principles like

  1. Single Responsibility Principle – An object should shoulder only one Responsibility.
  2. DRY (Don’t Repeat yourself)

References

  1. Patterns Wiki
  2. Cohesion by Edge pereira
  3. Bill Wagner’s Coupling
  4. Design Pattern Reference
  5. Kent Bank’s Coupling and Cohesion