Low Coupling
“How to support low dependency, low change impact, and increased reuse?” – Craig Larman
Coupling is a measure of how strongly one element is connected to, has knowledge of, or relies on other elements. Low Coupling is an evaluative pattern that dictates that you should assign responsibilities so that coupling remains low.
When to use
Use this as a metric to evaluate alternatives. When choosing between Design A and Design B, choose the one with lower coupling.
Why it matters
- Maintainability: Changes in one class don’t ripple through the whole system.
- Reusability: A class with no dependencies is easy to pick up and use in another project. A class that depends on 20 others brings the whole heavy graph with it.
- Understandability: You can study classes in isolation.
Signs of Violation
- A change in a private field of
Class Aforces you to updateClass B. - Circular dependencies (A depends on B, B depends on A).
- “Shotgun Surgery”: One small change requires edits in many files.
Explanation
Problem
High coupling makes systems fragile. “Spaghetti code” is essentially code with maximum coupling where everything touches everything else.
Solution
Minimize connections. Use interfaces. Use Dependency Injection. Encapsulate details.
Real world analogy
A modular Hi-Fi system. The speakers are loosely coupled to the amplifier via a standard cable. You can replace the speakers without replacing the amplifier. A boombox with built-in speakers has high coupling; if the speakers blow, the whole unit is trash.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- High Cohesion: Often goes hand-in-hand. Low Coupling + High Cohesion is the golden rule.
- DIP (Solid): A specific way to achieve low coupling.
Code example
Typescript
Bad (Violation)
Good (Adherence)
PHP
Bad (Violation)
Good (Adherence)