Object-Oriented Design

Coupling and Cohesion

Learned in CS247.

Coupling

Coupling describes of how strongly different modules depend on one another.

Low Coupling:

  • Function calls with primitive arguments / results
  • Function calls with structs / arrays as results
  • Modules affect each other’s control flow
  • Modules sharing global data

High Coupling:

  • 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

Cohesion describes how closely parts of a module relate to one another.

Module has a unifying common theme, e.g. <algorithm> Elements manipulate state over lifetime of an object, e.g.<fstream>

Low Cohesion:

  • parts of module are completely unrelated, e.g. <utility>

High Cohesion:

  • 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!

The Goal

We strive for: low coupling, high cohesion.

It is a careful balancing act. Everything is a Tradeoff.

Thoughts

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

  • I think talking with Hemal Shah about this is what he thinks about GXF

Loosely coupled \neq 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.