Engineering

Nouns: your program's dictionary

Name every concept once, model it once, and use that one model everywhere. Five slightly different Song classes is how codebases rot.

By Sean 3 min read

Every program is about something. A setlist app is about songs, setlists, keys, and tunings. A claims system is about claims, members, and providers. Those concepts are the program’s Nouns, and the first thing I do on any project is decide what they are, name them carefully, and model each one exactly once.

Then I use those Nouns everywhere. Every module, every function, every test speaks the same language. That’s the program’s dictionary, and it’s the foundation the rest of these notes are built on.

Five songs that should have been one

Here’s how it goes wrong. Nobody plans it; each of these was added by someone solving a real problem on a deadline:

# library/models.py
@dataclass
class Song:
    title: str
    key: str
    bpm: int


# setlists/setlist.py
@dataclass
class SetlistSong:
    name: str            # the same thing as Song.title
    song_key: str        # "Am"? "A minor"? "a-minor"? Depends who wrote it.
    tempo: float         # bpm again, but now a float
    duration_secs: int
    capo: int
    tuning_name: str


# export/pdf.py
class SongInfo(TypedDict):
    title: str
    key: str
    length: str          # "4:12", already formatted


def format_song_length(song: Song) -> str: ...
def format_setlist_song_length(song: SetlistSong) -> str: ...  # the same function again

Plus a TrackRow from the database layer and the raw dictionary that comes back from a web API. Now every boundary between modules needs a conversion, every conversion is a place to lose data or get it subtly wrong, and every helper function gets written two or three times, once per variation. Ask “what is a song in this program?” and the honest answer is “it depends which file you’re in.”

One Noun per concept

Here’s the same concept, modeled once:

from dataclasses import dataclass
from datetime import timedelta
from enum import StrEnum
from typing import NewType

SongId = NewType("SongId", str)


class MusicalKey(StrEnum):
    A_MINOR = "A minor"
    C_MAJOR = "C major"
    E_MINOR = "E minor"
    G_MAJOR = "G major"


class Tuning(StrEnum):
    DROP_D = "drop-d"
    OPEN_G = "open-g"
    STANDARD = "standard"


@dataclass(frozen=True)
class Tempo:
    beats_per_minute: int


@dataclass(frozen=True)
class GuitarSetup:
    """Everything about the guitar that has to change before the song starts."""

    capo_fret: int
    tuning: Tuning


@dataclass(frozen=True)
class Song:
    duration: timedelta
    guitar_setup: GuitarSetup
    key: MusicalKey
    song_id: SongId
    tempo: Tempo
    title: str

A few things are going on here, and each one is deliberate:

  • One name per idea. It’s title, everywhere, forever. Not name in one place and title in another.
  • No loose primitives. A key isn’t a str that might be “Am” or “A minor”. It’s a MusicalKey, and a typo is an error, not a new key. A duration is a timedelta, not an integer whose unit you have to guess from its name. Even an id gets its own type, so a SongId can’t be passed where some other string was expected.
  • Related fields are grouped. Capo and tuning are both “how the guitar needs to be set up,” so they live together in GuitarSetup instead of floating around as two more top-level fields. When I later add string gauge or a pickup selection, there’s an obvious place for it.
  • Fields are alphabetized. It sounds fussy, but when a model has fifteen fields, alphabetical order means you can tell at a glance whether a field exists. No scanning, no guessing.
  • It’s frozen. A Song can’t be changed after it’s created. Nothing can quietly reach in and edit one out from under you.

Don’t lose data

This one’s subtle. Say a function needs a song’s title and duration. It’s tempting to write this:

def describe(title: str, duration: timedelta) -> str: ...

and pass song.title, song.duration. But the moment you do that, everything downstream has lost the rest of the song. Next month, when the description should also mention the tuning, you’re changing the signature and every caller. Pass the Noun instead:

def describe(song: Song) -> str: ...

The function takes what it needs from the song, and everything else stays available for later. Same rule for return values: if you have a whole Song, return the whole Song.

Where outside data fits in

Data from outside the program (a database row, a web API’s JSON, a vendor library’s objects) is not a Noun. It gets converted into Nouns at the edge, in the one module that talks to that outside thing, and nothing past that edge ever sees the raw version. That’s what Wrap every vendor is about.

The result: inside the program, there’s exactly one way to say “song,” and every piece of code agrees on what it means. That’s what makes the pieces fit.