Recently there was a .NET architect position interview in polaris and this question was asked to almost all candidates. Lot of people were aware of coupling but not of cohesion. So below goes a full explanation in detail with examples.
If you look at the dictionary meaning of cohesion it means sticking things together which are of the same types or substance.
Cohesion in software is a measure which tells how strongly related the responsibilities of a class or module is.
For example below is a class diagram of a simple “customer” class. In this class diagram “CustomerName” and “CustomerCode” are very much related to the “Customer” class but watch the “SupplierCode” property it’s not related directly.
Because this class has unrelated elements it has LOW.
Now Customers buy products and have multiple addresses. So it’s logical to have “Customer” , “Product” and “Address” in this namespace but look at “Exception” and “Logger” classes they are needed but they are not logically the part of “Customer” namespace.
Coupling is a contrast to cohesion. Coupling says how much the classes and modules directly depend on each other. A good architecture is that architecture where change in one place should not lead to changes all over the places. If classes are directly connected with each other, then change in one class leads to changes in other class as well , so a loose coupling is more desirable.
Below is a simple class diagram which shows “Customer” and “Address” relationship. In the first section of the diagram “Customer” and “Address” classes are directly connected. In other words changes in “Address” class will lead to change in “Customer” class as well. So rather than these classes talk with each other directly they can talk via interfaces which the next section of the diagram shows. This is termed as decoupling.
|Cohesion||Classes and modules have related and logical elements together. This is a desirable situation.||Elements are unrelated and are not desirable.|
|Coupling||This means the classes are tightly coupled with each other and will make the software more difficult to maintain||This means that classes are not tightly coupled and changes in one place will not affect the other section. This is a desirable situation.|
In other words, good software architectures have high cohesion and low coupling.