Low Coupling¶
Principle
Ensure that classes are loosely coupled to one another.
Object-Oriented designers use the word coupling to describe the dependency between classes. When a class collaborates with another class, there is some sort of dependency between them and therefore they are coupled to each other.
Classes should not interact (collaborate) with too many other classes. Moreover, if a class A
interacts with another class B
, this interaction should be loose, which means that A
should not know too much (or make too many assumptions) about B
.
Why does this matter?
- Applications that are easy to change consist of classes that are loosely coupled.
- A class that is tightly coupled to other classes, may need to change if those classes change.
- In a system that is strongly coupled, when a class changes, there's a greater risk of breaking several other classes (that depend on the changed one).
How to figure out if coupling is high?
When you look at the UML Class diagram of your design, every "relationship" is an indication of coupling. The more relationships you have (and the stronger the relationships are)1, the higher is the coupling.
Sometimes, coupling does not manifest itself in a UML diagram. This is when, for instance, a class depends on the inner working of another class. This is the strongest (and nastiest) form of coupling.
Take home message
It may be impossible to eliminate coupling but you should strive to minimize it.
Example Design¶
The examples are (partial) designs for the CourseReVU App.
The bidirectional association between Course
and Review
below is an example of tight coupling; both the Review
and the Course
need to know about one another. If we change one, we may have to change the other one.
On the other hand, the example below represents loosely coupled classes. Here, there is still a dependency between Review
and Course
but only Review
knows about Course
and moreover, it only knows the id
of a course it is collaborating with.
-
Association, for instance, is a stronger indication of coupling than dependency relationship. ↩