Thursday, October 13, 2011

A short review of cohesion and coupling

Developing good quality software is something that we should always try to achieved. So here in this post I'll try to gently review two concepts that will hopefully help us get closes to the goal.  Cohesion and coupling are two factors that help to increase reliability, understandably, inefficiency, and maintainability within and between classes.

Cohesion measures the degree of interactions and how strongly-related are the responsibilities within a class. Low cohesion is a sign of bad design, high cohesion is the contrary.  Low cohesion is when a class has a bunch of unrelated responsibilities. If a class has responsibilities that don't relate to its name, than maybe they don't below there in the first place. A high cohesive class ensures strong related responsibilities.

Coupling is the measure of how interconnected classes are, how much a class relies on other classes. Tightly couple classes means that classes need to know about the internal details of the others.  There are many disadvantages to tightly couple systems mainly because a change to one class might force a change in the other, this can potentially create a ripple effect to other classes.  Classes that are tightly couple can also be difficult to unit test because dependent classes have to be included.  If tight couple systems are not ideal, than how do we achieve loosely coupling? classes are loosely couple when changes in one class rarely or never involved changes in the other. One way to achieve loosely coupling is to make classes interact with others through a well defined and stable interface, after all they shouldn't be concerned with the other's internal implementation.

The higher the cohesion and the lower amount of coupling tends to lead to a good system design. Thinking about these concepts the next time we find ourselves writing some software will definitely make a good difference.

No comments:

Post a Comment