Tuesday, May 3, 2011

Cohesion and Coupling

Cohesion and Coupling deal with the quality of an OO design. Generally, good OO design calls for loose coupling and high cohesion. The goals of OO designs are to make the application

* Easy to Create
* Easy to Maintain
* Easy to Enhance


Coupling is the degree to which one class knows about another class. Let us consider two classes class X and class Y. If class X knows class Y through its interface only i.e. it interacts with class Y through its API then class X and class Y are said to be loosely coupled.

If on the other hand class X apart from interacting class Y by means of its interface also interacts through the non-interface stuff of class Y then they are said to be tightly coupled. Suppose the developer changes the class Y‘s non-interface part i.e non API stuff then in case of loose coupling class X does not breakdown but tight coupling causes the class X to break.

So its always a good OO design principle to use loose coupling between the classes i.e all interactions between the objects in OO system should use the APIs. An aspect of good class Xnd API design is that classes should be well encapsulated.

Cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Coupling is all about how classes interact with each other, on the other hand cohesion focuses on how single class is designed. Higher the cohesiveness of the class, better is the OO design.

Benefits of Higher Cohesion:

* Highly cohesive classes are much easier to maintain and less frequently changed.
* Such classes are more usable than others as they are designed with a well-focused purpose.

No comments:

Post a Comment