Monday, August 13, 2012

Coupling Vs Cohesion

Today I am going to address very simple question/topic yet very often asked in Java interviews.

First of all, Coupling and Cohesion, both, are very different in their meaning even though they may sound similar. I shall try to explain using plain examples.

Coupling:

Coupling is a measure of how closely two things are bound together, known to each other and dependent on each other. In OOP and Java, two classes C1 and C2 are said to be tightly coupled if a third class C3 can not  use C1 without knowledge of C2.
Usually this happens when the class C1 holds a reference of C2 as it's member or static variable.



A good program or software should avoid tight coupling as much as possible.

Cohesion:

Cohesion is the measure of keeping logically related(and only related) things together in a group. In Java, a high cohesion is achieved by defining only logically or meaningfully related functions in a class.

Example 1:

A Calculator class should define functions such as add(), subtract(), multiply() etc. It should, however, never define a function to walk(), which clearly is an unrelated function for the  Calculator class.



Example 2:

Similarly, a DateUtility class should define functions such as formatDate(), parseDate(), isAfterDate(), isBeforeDate() etc. It should, however, never define a function to reverseString(), which clearly is an unrelated function for a DateUtility class.


A good program or software should possess high cohesion as much as possible,

So essentially, a good program or software should possess loose coupling and high cohesion among its components.