Code Craft & Best Practices

Introduce Clean Code to a Legacy Backend Without a Rewrite

The fastest way to make an inherited backend harder to maintain is to apply clean code patterns everywhere at once. A renamed service, a new interface, and a tidier database layer can each look sensible while collectively changing behavior nobody documented. I would introduce patterns only at a boundary I am already changing, and require evidence that the old behavior still holds before improving the design behind it.

The first patch should record behavior, not improve style

Pick one handler that has a real reason to change: a bug to fix, a feature to add, or a recurring source of difficult reviews. Do not begin with the repository’s largest file merely because it is ugly; its size says little about which behavior you can safely verify. Give the first attempt a provisional limit of one handler, so a failed experiment remains cheap to discard.

Before moving code, trace that handler from its HTTP entry point to its database writes and external calls. Note the request fields it accepts, the status codes and headers it returns, and whether retries can repeat a write. For an HTTP API, RFC 9110 is more useful here than a naming convention because changing a response from 404 to 400 is observable even if the new code reads better. If the handler uses PostgreSQL 16, record transaction boundaries and any ordering that clients might rely on; an extracted function must not quietly commit earlier.

Write characterization tests for behavior you find, including behavior you dislike. The following Python 3.12 example is deliberately small and runs as written with python3 example.py. In a real repository, replace legacy_fee with a call into the existing code before editing its implementation.

import unittest

def legacy_fee(cents, tier):
    return max(0, cents // 100) if tier == "basic" else 0

class ExistingBehavior(unittest.TestCase):
    def test_boundary(self):
        self.assertEqual(legacy_fee(99, "basic"), 0)
        self.assertEqual(legacy_fee(100, "basic"), 1)

    def test_unknown_tier(self):
        self.assertEqual(legacy_fee(100, "unknown"), 0)

if __name__ == "__main__":
    unittest.main()

The unknown tier may deserve an error eventually. Preserve its current result in the refactoring patch because mixing a behavior change with a structural change makes failures harder to diagnose. This example exercises two tests and three assertions; those are properties of the snippet, not evidence that an actual fee service is adequately tested. Add cases from production bug reports and observed boundary values rather than copying the example’s numbers as policy.

Use Clean Code Patterns Every Developer Should Know as vocabulary for a candidate change, not as a queue of work, because a named pattern does not establish what callers depend on. The first review should make a narrower claim: “These inputs still produce these outputs, and this database write still occurs in the same transaction.”

A small seam is safer than a new layer for every class

Once the tests describe the current behavior, look for the smallest place to separate a decision from an effect. A fee calculation embedded in a request handler might become a plain function that takes amounts and returns an amount. Keep the HTTP parsing, database call, and response formatting where they are initially. This gives the calculation a testable boundary without requiring a new service hierarchy.

Inline extraction wins when one caller owns a mostly pure block of logic: moving that block into a function costs little review time and introduces no runtime routing. It costs you a narrow seam that may need changing if another caller appears. Branch by abstraction wins when several callers share a side-effecting dependency or you need to replace an implementation gradually: an interface or adapter lets old and new implementations coexist. It costs an extra dispatch point, temporary duplicate paths, and tests proving both paths honor the same contract. Neither option wins because it produces more files.

For a backend developer new to clean code patterns, an adapter is useful when it contains an actual external boundary. A wrapper around a PostgreSQL query can make transaction ownership explicit; a wrapper around a one-line arithmetic expression often just hides the expression. If you introduce an interface, name the operation in the caller’s terms—reserve_inventory, for example—rather than mirroring every method of the database client. That keeps the interface tied to a behavior you can test.

I would not replace every conditional with polymorphism, because a short, stable conditional is easier to inspect than several classes whose only purpose is to avoid if. I would challenge Clean Code Patterns Every Developer Should Know as an adoption schedule for the same reason: the appropriate pattern depends on where behavior varies, not on whether the repository has used every pattern in a catalog.

Keep the first extraction in a separate commit from any intentional behavior change. Git’s git diff --check catches whitespace errors, but the more valuable review aid is a diff in which a reviewer can pair the old branch with the new function line by line. If the extraction requires changing route names, error handling, and persistence at once, the proposed seam is probably too broad for a first patch.

A green unit suite cannot prove that an API stayed compatible

Unit tests establish facts about the functions they exercise. They cannot, by themselves, establish that serialization, database timing, or HTTP behavior is unchanged. Before the refactor, capture a small set of representative requests and responses with sensitive values removed. Include successful requests, a missing resource, invalid input, and a retry of a write. Set zero changed response fields as the acceptance target for a behavior-preserving patch; treat that as a target to check, not a result you have already measured.

Run the same cases against the patched handler in an isolated environment. Compare status, headers that clients use, JSON fields, and relevant database rows. Normalize values that are meant to vary, such as generated IDs and timestamps, but do not normalize away a changed error code just to obtain a passing comparison. If clients depend on ordering, compare order too; a test that converts every result to a set would conceal a regression.

For Python services, pytest 8 and pytest-cov 5 can run focused tests with pytest -q tests/test_orders.py --cov=app.orders --cov-branch. Branch coverage helps reveal an untested error path, but a percentage alone does not show whether the assertions describe the right outcome. Coverage.py 7 can supply the underlying branch data. Keep the test command focused while iterating, then run the repository’s full suite before merging so a change in a shared helper is not missed.

Where another service consumes the API, a Pact 4 consumer contract test can check the fields that consumer expects. Contract tests win when a consumer can state its dependency precisely; they cost coordination and maintenance when the consumer changes. Recorded request comparisons win when you are still discovering existing behavior; they cost careful scrubbing and can miss cases you did not record. Use both only when each answers a question the other cannot.

Production signals provide another check after deployment. Compare the handler’s OpenTelemetry http.server.request.duration histogram and error rate against a baseline from the same route, and inspect query counts through PostgreSQL’s pg_stat_statements extension if it is already available. Record the measured p95 latency and query count before the patch rather than inventing a universal acceptable percentage. A cleaner-looking abstraction that adds a query per request has a cost a unit test is unlikely to expose.

Enforce the new rule at the touched boundary, not across the repository

After the first safe extraction, make its convention easy to repeat. Document where input validation ends, which function owns the business decision, and which component owns the transaction. A short example beside the changed module is more useful than a repository-wide decree because the next developer can compare it with working code. Require the convention in code review for that boundary before extending it elsewhere.

Automation should support that limited scope. Ruff 0.9 can check a changed Python file with ruff check --select E4,E7,E9,F app/orders.py; those selected rules catch particular errors without imposing a large formatting diff on untouched modules. If you add mypy 1.15, start with the extracted function and its inputs rather than demanding types for every imported legacy object. An adjustable 30-minute investigation budget for a newly reported typing or lint failure is reasonable for an initial trial: if resolving it requires unrelated rewrites, narrow the check and file the broader work separately.

Avoid making test doubles the architecture. Mock an external payment call or clock when the real effect would make a test unreliable, but run an integration test against the actual database path when transaction behavior is the claim. An in-memory substitute can answer whether a function calls save(); it cannot reliably answer whether PostgreSQL constraints, isolation, or SQL ordering still behave the same way.

Judge adoption by changes reviewers can verify: fewer unexplained branches in the touched path, a characterization test for a previously untested outcome, and no unintended API or query changes. Do not count new interfaces as progress, because their existence says nothing about whether a future bug will be easier to locate. If the next feature still requires editing the handler, its extracted decision function, and several forwarding classes, remove a layer before adding another pattern.

Start with a handler you can observe tomorrow

Choose one upcoming handler change and save its current request, response, and relevant database result before touching the code. Add a test for one surprising boundary case, then extract only the decision that the change requires. Open a review with the before-and-after evidence attached. If you cannot state what remained unchanged, stop there and improve the observation before attempting a larger refactor.