SCJP Study Guide:
OO Concepts


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Loose coupling and high cohesion XyzWs SCJP Study Guide: Loose coupling and high cohesion

Loose coupling and high cohesion


One of the most important goals of object oriented design is to have high cohesion classes and loose coupling between these classes.

Coupling refers to links between separate units of a program. In object oriented programming, if two classes depend closely on many details of each other, we say they are tightly coupled.

Coupling is a measure of the interdependence between classes. If every object has a reference to every other object, then there is tight coupling, and this is undesirable. Because there's potentially too much information flow between objects. Loose coupling is desirable. It means that objects work more independently of each other. Loose coupling minimizes the "ripple effect" where changes in one class cause necessity for changes in other classes.

Cohesion, on the other hand, refers to the number and diversity of tasks that a class is designed for. If a class is responsible for a few related logical tasks, we say it has high cohesion.

Cohesion is a measure of strength of the association of variables and methods within a class. High cohesion is desirable because it means the class does one job well. Low cohesion is bad because it indicates that there are elements in the class which have little to do with each other. Modules whose elements are strongly and genuinely related to each other are desired. Each method should also be highly cohesive. Most methods have only one function to perform. Don't add extra instructions into methods that cause it to perform more than one function.

Loose coupling makes it possible to:

  • Understand one class without reading others
  • Change one class without affecting others
  • Thus: improves maintainability

High cohesion makes it easier to:

  • Understand what a class or method does
  • Use descriptive names
  • Reuse classes or methods

It is always easier said than done. How do I know what design is high cohesive and loose coupling? There's a metric to help you verify that you've designed a cohesive class, and a Demeter's Law to help you measure the coupling between classes. For more details refer to "Coupling and Cohesion: The Two Cornerstones of OO Programming" .


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |