Skip to content

Writing maintainable code

Phase 1 · Working like an engineer · 15 min read

What you'll be able to do

  • Turn a notebook-style script into functions whose inputs, outputs, and side effects are visible.
  • Choose boundaries between modules so changes and tests stay local.
  • Review a refactor for behavior, error handling, and unnecessary complexity.

Maintainability is about the next change

Code is maintainable when another person, including future you, can read it, change it, and test the change without tracing the whole program. In a long-lived codebase, you repeatedly read and change existing code, so optimize for that work, not for the fewest lines typed today.

Some complexity is essential: a classifier really needs a rule for turning observations into predictions. Accidental complexity comes from our choices: a hidden global threshold, a function that also opens a file and prints, or a call chain that circles back through its own modules. The goal is to make the essential rule visible while removing avoidable work around it.

For example, predict_label(signal, threshold) tells a reader what varies. do_it(x) makes them inspect the body and every caller. A function can be ten lines and still do three unrelated things, or thirty lines and tell one coherent story.

Start with the boundaries around a function

A pure function returns the same result for the same inputs and does not change anything outside itself. It is easy to test because a test can call it directly:

def predict_label(signal: int, threshold: int) -> int:
    return int(signal >= threshold)

assert predict_label(7, 5) == 1

Reading a file, calling a model service, writing to a database, and printing are side effects. They are necessary, but put them at the edge of the program. In plain terms, calculate in the middle; do I/O around it. Then tests can feed the calculation ordinary values and exercise the I/O boundary separately.

Cohesion asks whether the things in a module belong together. A features.py containing feature transformations is cohesive; a growing utils.py containing CSV parsing, retries, and model scoring is not. Coupling asks how much one part must know about another. If feature code imports the command-line entry point just to read its globals, a small CLI edit can break training. Let the entry point depend on feature and model modules, not the reverse. That direction also avoids circular imports, where two modules need each other before either has finished loading.

Dependencies point one way: the entry point uses the core, the core never imports the entry point.

A notebook script before and after

Here is a compact version of a familiar notebook workflow. It loads data, cleans it, trains a majority-class model, evaluates, and prints. The hidden dependencies are the globals and file path; rerunning cells out of order can leave rows or majority from a previous run.

from pathlib import Path

DATA_PATH = Path("data/train.csv")
MIN_SIGNAL = 0
rows = []
counts = {0: 0, 1: 0}

for line in DATA_PATH.read_text().splitlines():
    if not line or line == "signal,label":
        continue
    signal_text, label_text = line.split(",")
    signal = int(signal_text)
    label = int(label_text)
    if signal < MIN_SIGNAL:
        continue
    rows.append((signal, label))

seen = set()
cleaned = []
for row in rows:
    if row in seen:
        continue
    seen.add(row)
    cleaned.append(row)

for signal, label in cleaned:
    counts[label] += 1
if counts[0] >= counts[1]:
    majority = 0
else:
    majority = 1

correct = 0
for signal, label in cleaned:
    prediction = majority
    if prediction == label:
        correct += 1
if cleaned:
    accuracy = correct / len(cleaned)
else:
    accuracy = 0.0
print(f"accuracy={accuracy:.3f}")

The cleanup does not require the filesystem. Extract it first, then move the data rule into a separate module. The following version shows the dependency direction: core.py knows about rows and predictions; cli.py knows where the file is. The reader is injected: pass the thing that reads data in as an argument. A test can pass a function returning in-memory lines.

# core.py
from dataclasses import dataclass
from typing import Callable, Iterable

Row = tuple[int, int]

@dataclass(frozen=True)
class Config:
    min_signal: int = 0

def parse_rows(lines: Iterable[str]) -> list[Row]:
    rows = []
    for raw in lines:
        line = raw.strip()
        if not line or line == "signal,label":
            continue
        parts = line.split(",")
        if len(parts) != 2:
            raise ValueError("expected signal,label")
        signal, label = (int(part) for part in parts)
        if label not in (0, 1):
            raise ValueError("label must be 0 or 1")
        rows.append((signal, label))
    return rows

def clean(rows: Iterable[Row], min_signal: int) -> list[Row]:
    return list(dict.fromkeys(row for row in rows
                              if row[0] >= min_signal))

def train(rows: Iterable[Row]) -> int:
    labels = [label for _, label in rows]
    if not labels:
        raise ValueError("no training rows")
    return int(labels.count(1) > labels.count(0))

def evaluate(majority: int, rows: Iterable[Row]) -> float:
    labels = [label for _, label in rows]
    if not labels:
        raise ValueError("no evaluation rows")
    return sum(label == majority for label in labels) / len(labels)

def run(read_lines: Callable[[], Iterable[str]], config: Config) -> float:
    rows = clean(parse_rows(read_lines()), config.min_signal)
    return evaluate(train(rows), rows)
# cli.py
from pathlib import Path
from core import Config, run

if __name__ == "__main__":
    path = Path("data/train.csv")
    print(f"accuracy={run(lambda: path.read_text().splitlines(), Config()):.3f}")

This is a structural example, not a sound ML evaluation: measuring accuracy on training rows inflates the estimate of generalization. A real experiment reads an independent holdout set and records its split and seed. The lab separates reader calls, not data independence; a real holdout needs disjoint rows.

This version also deliberately changes the empty-data contract from returning 0.0 to raising ValueError, and gives malformed labels an explicit error. Decide and test such contract changes separately from the structural refactor.

Choose abstractions that pay for themselves

A class helps when related data and behavior must travel together, or an object needs state across calls. A plain record is often a dataclass; a stateless transformation can stay a function. For a dependency such as a reader or model client, passing a callable is often enough. If several operations must be provided together, a small typing.Protocol can describe them without forcing inheritance. That is an interface by behavior: callers care what the object can do, not its family tree.

from typing import Iterable, Protocol

class Reader(Protocol):
    def __call__(self, source: str) -> Iterable[str]: ...

Type hints document the shape of data and improve editor completion. A type checker such as mypy or pyright can catch a caller passing str where int is expected before the call runs. Add hints gradually at boundaries first. Hints do not validate CSV contents at runtime, and every local variable need not be annotated.

Validate untrusted data when it enters the program. Raise a specific ValueError for malformed rows or an empty training set so the failure is close to its cause. Return a value for an ordinary result, including a legitimate zero accuracy; raise for a condition the caller cannot treat as a normal result. Catch an exception only where you can add context or recover. Catching Exception and continuing can turn a broken experiment into a plausible metric. Put paths, thresholds, and seeds in a configuration object instead of scattered mutable globals.

SOLID and DRY are prompts for judgment, not laws. If the same three lines occur twice, duplication may be cheaper than a shared abstraction that guesses what future callers need. The rule of three says to reconsider after a third repetition: compare the actual cases and extract the common rule if it is stable. Deep inheritance built to satisfy an acronym usually makes the next change harder.

Refactor and review in small steps

Before changing structure, pin down behavior with tests: normal rows, malformed input, empty data, and repeated runs. Then make one change at a time: rename an unclear value, extract a calculation, or inline a wrapper that hides rather than explains. Run the tests after each step. A long function, a god class that owns everything, a boolean flag such as process(rows, training=True), and feature envy (one module repeatedly reaching into another's internals) are clues to inspect, not commands to split code automatically.

Use this checklist on your own diff:

  • Can a reader tell what each function does from its name and arguments?
  • Are file, network, database, and model calls outside the calculation being tested?
  • Does each module depend in one direction, without reaching into another module's globals?
  • Are invalid inputs rejected at the boundary with useful errors?
  • Do tests cover the behavior that could change, including two runs in one process?
  • Did this diff remove complexity, or introduce an abstraction with no current user?

Formatters and linters such as black and ruff automate style checks, so review can focus on behavior and design.

For AI engineers

For AI engineers

A training script often hides paths and magic numbers in cells, then reads global variables left by an earlier cell. Moving it into a package exposes the stages: data loading, feature code, model code, and evaluation. Put settings in a dataclass, pass readers and model clients in, and save the config, random seed, and commit hash with each result. Those records make an experiment easier to reproduce; they do not replace a fixed data snapshot or a true holdout set.

Common mistakes

  • Building a deep inheritance hierarchy before there are multiple real implementations.
  • Putting unrelated helpers in one huge utils.py, then importing it everywhere.
  • Using boolean flag parameters that make one function follow two different workflows.
  • Mutating global configuration so a second run depends on the first.
  • Catching Exception, printing an error, and continuing with incomplete results.
  • Writing comments that repeat the code while leaving the reason for a threshold unexplained.

Check yourself

A parser reads a CSV file and computes accuracy in one function. What would you separate first, and how would you test it?

Separate file reading from parsing and accuracy. Pass lines to a parser, then pass parsed rows to evaluation. Test each with in-memory values; keep one small test for the file boundary.

A function score(rows, debug=True) prints intermediate predictions. What design change would make repeated tests simpler?

Return the predictions or score from a pure function. Let the caller decide whether to print. The calculation then has no output side effect and needs no debug flag.

Two modules import each other to share a configuration constant. Where should the dependency point?

Put configuration in a small data object passed from the entry point, or move truly shared definitions to a lower-level module. Both modules can depend on that object; neither needs to import the other.

You find the same three lines in two places. Must you extract a helper now?

No. Check whether the cases express the same rule. A premature helper can couple changes that should stay separate; revisit after a third real use.

Lab

Refactor a working but tangled majority-class experiment in code/code-design/. Implement parsing, cleaning, training, and evaluation as separately testable functions. Pass a reader and frozen configuration to the experiment runner; use separate training and evaluation sources. The tests use an in-memory reader and repeat runs to catch leaked state. Run cd code/code-design && PYTHONPATH=starter python -m pytest tests -q. You are done when every test passes without changing the tests.

Go deeper