Friday, November 17, 2006

Coupling and Cohesion

Coupling refers to how tightly connected classes are. If a class is very dependent on other classes to carry out its functions, then it is strongly coupled.
Strongly coupled classes can lead to problems in program design. Because such classes are interdependent, they are difficult to extend, and bugs in one can affect others.

This interdependency can also make it difficult for other programmers to understand programs that contain such classes.
To perform adequately, classes must be connected to other classes. But you should choose a level of connection that doesn't make one class too dependent on another.

This is particularly important when you design for inheritance.
Though inheritance is a form of coupling, it can make programs easier to design and extend.

So when choosing classes, you need to balance the requirements of inheritance against the need for weak coupling.

Cohesion is a measure of how closely related the elements in a class are. These elements are the states, behaviors, and functionalities of the class.
A class whose members are simply grouped together and have little in common is only coincidentally cohesive. Such a class might have two unlinked functions, or it may group object states with unrelated object behavior.

Because its elements do not cohere to realize a single purpose, such a class is confusing, difficult to use, and often too complex to implement.
Let's say you used a class named BankEmployee to model how bank staff are paid and how they interact with customers.

Since the elements of these separate functionalities are unrelated, this class would be a bad abstraction.
Classes with good cohesion are well defined and contain elements that properly belong together.

Such classes are easy to understand and use because they serve a definite purpose – they have functional cohesion.

No comments: