Coupling and Cohesion
Learned in CS247.
Coupling describes of how strongly different modules depend on one another.
- Function calls with primitive arguments / results
- Function calls with structs / arrays as results
- Modules affect each other’s control flow
- Modules sharing global data
- Modules have access to each other’s implementation (friend)
Ideally, we desire low coupling:
- easier to reason about our program
- easier to make changes
Cheat at Coupling: If I put everything in one class, super low coupling!
There exists a counterbalancing force: Cohesion.
Cohesion describes how closely parts of a module relate to one another.
Module has a unifying common theme, e.g.
Elements manipulate state over lifetime of an object, e.g.
- parts of module are completely unrelated, e.g.
- Elements are cooperating to perform exactly on task
Cheat at Cohesion: If I put every function in its own class, then they each do only one thing!
We strive for: low coupling, high cohesion.
It is a careful balancing act. Everything is a Tradeoff.
Equating loosely coupled with “good” and tightly coupled with “bad” can lead to a what Martin Fowler calls the Architect’s Dream, the Developer’s Nightmare: a system that is very flexible, but very difficult to work with. Source
Loosely coupled Best
Tightly coupled systems are generally more efficient than loosely coupled systems because the constraints imposed by the tight coupling allow optimization at build-time.