Engineering

Interfaces with no surprises

Prefer pure functions, compute instead of storing state, name every side effect, and never swallow an error. A good API does exactly what it says.

By Sean 3 min read

A beautiful API is one where you can read the name and the types and know exactly what will happen. No fine print. No “oh, it also does this.” Most of the hard bugs I’ve chased weren’t in complicated algorithms. They were in something that quietly did more than it said, or in a piece of state that got out of sync with reality.

Prefer pure functions

A pure function takes inputs, returns an output, and does nothing else. Same inputs, same output, every time. It doesn’t read a global, doesn’t change its arguments, doesn’t write anything anywhere.

def describe_setlist(setlist: Setlist) -> str:
    """A printable set: one line per song, with what to change on the guitar before it."""
    lines = [f"{setlist.name} ({_format_minutes(setlist.total_duration.total_seconds())})"]
    lines += [
        _describe_song(position, song) for position, song in enumerate(setlist.songs, start=1)
    ]
    return "\n".join(lines)

You can call that a thousand times in any order and nothing changes. It’s trivial to test (give it a setlist, check the string), trivial to reuse, and impossible to break by calling it at the wrong moment. Most of a well-built program can be written this way. The parts that truly have to touch the outside world (saving, sending, reading a clock) get pushed out to the edges, behind interfaces.

Compute it, don’t store it

Here’s a classic. A setlist keeps a running total of its length:

class Setlist:
    def __init__(self) -> None:
        self.songs: list[Song] = []
        self.total_seconds = 0

    def add_song(self, song: Song) -> None:
        self.songs.append(song)
        self.total_seconds += int(song.duration.total_seconds())

    def remove_song(self, song: Song) -> None:
        self.songs.remove(song)
        self.total_seconds -= int(song.duration.total_seconds())

It works until someone edits songs directly, or adds a replace_song and forgets to update the total, or a song’s duration gets corrected after it was added. Now there are two sources of truth, the list and the number, and they disagree. Those bugs are miserable to find, because the code that broke the total ran long before the code that shows it.

The fix is to not keep the state at all:

@dataclass(frozen=True)
class Setlist:
    name: str
    songs: tuple[Song, ...]

    @property
    def total_duration(self) -> timedelta:
        return sum((song.duration for song in self.songs), start=timedelta())

The total is computed from the songs, so it can’t ever be wrong. And the setlist is frozen, so nothing can change it out from under anyone. If I want a different setlist, I make a new one. Unless there’s a real, measured reason to cache something, I don’t keep state I can compute.

Name every side effect

Sometimes a function has to change the world: save a file, send a request, write to a database. That’s fine. What’s not fine is a function whose name hides it:

def get_song(song_id: SongId) -> Song:
    song = _read_song(song_id)
    _audit_log.write(f"read {song_id}")  # surprise: a read writes
    _recently_viewed.append(song)        # surprise: and changes global state
    return song

Nobody calling get_song expects it to write anything. So someone calls it in a loop to build a report, and now the audit log is full of fake reads and the “recently viewed” list is garbage. If a function has a side effect, the name says so (save_song, send_invoice, record_song_view), and if a module does something non-obvious behind its interface, the interface’s documentation says so up front.

Never swallow an error

The quietest surprise of all:

try:
    chart = chord_chart_service.find_chord_chart(song)
except Exception:
    chart = None  # "it's fine"

Now a broken API key, a network outage, and a song with no chart all look exactly the same, and nothing anywhere says anything went wrong. Errors should be specific and typed, so the code that can actually handle one can catch exactly that one:

class ChordChartUnavailableError(Exception):
    """The chart couldn't be fetched. The underlying reason is logged, never shown."""

And one more rule on errors: the raw underlying message (a stack trace, a vendor’s error text, a SQL error) never reaches the person using the software. It goes in the logs, where it’s useful. The person gets a clear message that doesn’t expose the program’s internals. That’s both friendlier and safer.

The result

When every function does what its name says, takes everything it uses as an argument, and keeps no state it could compute, you can understand any piece of the program by reading that piece alone. That’s what “no surprises” means, and it’s most of what makes software pleasant to change.