Cohesion, coupling, and changing one thing in one place
Each module does one job and hides how. Callers use its interface and nothing else, so changing a behavior means editing one place.
If I could only teach one thing about software design, it’d be this: high cohesion, low coupling. Everything else is a way of getting there.
- Cohesion is how well the things inside a module belong together. A cohesive module has one job, and everything about that job lives inside it.
- Coupling is how much modules know about each other. Loosely coupled modules talk through a small interface and know nothing about each other’s insides.
The test I use is simple: when I need to change one behavior, how many places do I have to edit? The answer should be one. If it’s more than one, something that belongs together has been spread apart, or something that should be hidden has leaked out.
A module is a boundary
A module isn’t necessarily one file. In Python, I treat a package as the module: its __init__.py is the public interface, and everything else inside it is internal. Internal files start with an underscore, and nothing outside the package ever imports them.
gigbook/
├── nouns/ The program's dictionary: Song, Setlist, Tuning...
├── config/ Settings. The only code that reads the environment.
├── storage/
│ ├── __init__.py Public: SongStorage, SongNotFoundError, S3SongStorage
│ ├── _song_storage.py The SongStorage interface
│ ├── _s3_song_storage.py The S3 implementation. The only file that knows S3 exists.
│ └── _song_serialization.py Songs to JSON and back
├── chord_charts/ Looking up chord charts from a web service
├── app_context/ Builds everything and hands it out
├── setlists/ Putting songs together into a set
└── main.py
The public surface is just a list of what the package offers:
# gigbook/storage/__init__.py
"""Saving and loading songs. Callers get Songs back, and never learn where they're kept."""
from gigbook.storage._s3_song_storage import S3SongStorage
from gigbook.storage._song_storage import SongNotFoundError, SongStorage
__all__ = ["S3SongStorage", "SongNotFoundError", "SongStorage"]
This is what lets a module stay cohesive without turning into one giant file. The storage package can be split into as many internal files as makes sense, and it can use whatever it wants internally, vendor libraries included. None of that matters to anyone outside, because they only ever see the interface. (Python doesn’t enforce underscores on its own, so I make the build enforce it. See Make Python fail when a boundary is crossed.)
A leaky interface
Here’s what high coupling looks like up close. This cache works, but only if every caller knows how it works inside:
class SongCache:
def __init__(self) -> None:
self.is_loaded = False
self.songs: dict[SongId, Song] = {}
def load_from_disk(self) -> None: ...
# Every caller, everywhere:
if not song_cache.is_loaded:
song_cache.load_from_disk()
song = song_cache.songs[song_id] # a KeyError if it's missing, so callers need to know that too
Every caller has to know that the cache must be loaded first, that songs live in a dictionary called songs, and what happens when a song is missing. That knowledge is now copied into every place that reads a song. If the cache ever changes (loading lazily, say, or keeping songs somewhere else), every one of those callers breaks.
The fix is to make the module own its own job:
class SongStorage(Protocol):
def load_song(self, song_id: SongId) -> Song:
"""Raises SongNotFoundError when no song has this id."""
...
def save_song(self, song: Song) -> None: ...
A caller asks for a song and gets a Song, or a clear, typed error. Whether there’s a cache, a disk, or a cloud bucket behind it, and whether anything has to be loaded first, is the module’s business. If a caller has to understand a module’s internals to use it safely, that’s a leak, and the fix goes in the module, not in the callers.
Changing one thing in one place
Here’s the same idea from the other direction. Where gigbook keeps songs in S3, each song is one object with a key like songs/little-wing.json. That key format lives in exactly one function, inside the storage package:
def _to_object_key(song_id: SongId) -> str:
return f"songs/{song_id}.json"
If setlist code built that string itself, and the export code did too, then renaming the folder in the bucket would be a hunt through the whole codebase, and missing one would be a bug that only shows up in production. Kept in one place, it’s a one-line change. Same for the URL of the chord chart API, the shape of its JSON, the name of an environment variable. Every one of those facts has exactly one home.
This website works the same way, in TypeScript. Every internal URL on binturongaudio.com is built in one file, so templates never write a path by hand:
export const routes = {
about: "/about/",
devlog: "/devlog/",
devlogPost: (postId: string): SitePath => `/devlog/${postId}/`,
engineeringNote: (noteId: string): SitePath => `/engineering/${noteId}/`,
home: "/",
// ...
} as const satisfies Record<string, SitePath | ((identifier: never) => SitePath)>;
Renaming a section of the site is an edit to that file, and the type checker finds anything that needs to follow.
Don’t over-slice it
Cohesion doesn’t mean making everything as small as possible. A module carved into twenty one-line files, each with its own interface, is just as hard to work in as one huge file. I aim for well-defined Nouns, modules that each have one reason to exist, and functions that each do one thing. If a piece stops making sense on its own, it’s too small.
When it’s right, it feels like Lego: every brick is complete on its own, and the only thing the next brick needs to know about it is the studs on top.