esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Letโ€™s talk

Iโ€™ll build the agent for it.

Refactor Messy Code Into Testable Code

How to split tangled code into small rules and passed-in services that tests can reach, with tests first, explained simply for your AI interview.

In short

Refactoring for testability means splitting code that mixes rules with calls to databases, models and email, so the rules can be tested alone. Keep the behaviour the same, write tests first, and pass the outside world in as an argument.

10 min readIntermediateCommon ยท estimateFacts checked 27 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

Messy code mixes the rules with calls to the database, the model and the inbox, so a test would touch real systems. I refactor in small steps. First I write tests that pin down what the code does today. Then I pull the rules into plain functions and pass the database, model and mailer in as arguments. Tests give them fake versions, so they run fast, cost nothing and can't email a customer.

What is refactoring for testability, in plain words?

Code is easy to test when you can check one piece without starting the rest of the system. Messy code is the opposite: the piece you want to check is tangled up with the database, the model and the email server, so every check drags all of them in.

Refactoring means changing how code is arranged without changing what it does. For testing, that usually comes down to three moves: pull the rules into plain functions, pass the outside services in as arguments, and keep the wiring in one thin place.

Think of a bank teller who also holds the vault keys, answers the phone and prints the statements. You can't check the teller's sums without the vault, the phone line and the printer. Split the jobs and each one can be checked alone. An AI app works the same way: the model call is the phone line, slow and costly, so it goes behind a simple seam: one narrow entry point that the rest of the code calls.

Key words

Pure function
Same inputs, same output, and no calls to anything outside: no database, no network, no email.
Side effect
Anything the code does beyond returning a value: writing to a database, calling an API, sending mail.
Dependency injection
The caller hands a function the services it needs, instead of the function fetching them itself.
Fake
A small stand-in for a real service that returns fixed answers, so a test runs without the real one.
Characterisation test
A test that records what the code does today, so you notice if a later change moves it.

Which moves make messy code testable?

  • Messy

    One function does everything

    It loads the claim, asks the model, works out the payout and sends the email in one 400-line function.

  • Testable

    Rules apart, wiring thin

    The payout is a plain function. The database, model and mailer come in as arguments.

Dependency injection is the fix. Microsoft's .NET guide describes the same trap and the cure: the hard-wired version "is difficult to unit test", and the cure is an interface or base class, with the real version registered in a service container, so the class using it does not choose it.

  • โ€œThis implementation is difficult to unit test.โ€

    Microsoft, .NET dependency injection

Python's standard unittest.mock library does the same job in tests. It swaps the real services for stand-ins that record how they were used, so you do not hand-write one for each service.

Here is the payout rule pulled out. It takes plain numbers and a yes/no flag, so the test needs no database, no model and no email. The four made-up claims are the test. A claim smaller than the excess pays zero, so the rule never goes negative.

Python
# Payout rule, pulled out of the function that talks to the database and the mailer.
def payout_for(amount, policy_limit, excess, flagged):
    if flagged:
        return 0  # a person must review flagged claims first
    return max(0, min(amount, policy_limit) - excess)

# The test: made-up claims, no database, no model, no email.
cases = [
    ((1200, 1000, 100, False), 900),
    ((800, 1000, 100, False), 700),
    ((1200, 1000, 100, True), 0),
    ((50, 1000, 100, False), 0),
]
for args, expected in cases:
    got = payout_for(*args)
    print("PASS" if got == expected else "FAIL", args, got)

Output

PASS (1200, 1000, 100, False) 900
PASS (800, 1000, 100, False) 700
PASS (1200, 1000, 100, True) 0
PASS (50, 1000, 100, False) 0

After: the rule is a plain function

Fake claim

a small made-up record

Fake model answer

a fixed reply, no API call

payout_for()

same input, same answer, no I/O

Expected payout

the test compares, then passes or fails

  1. 1The test passes in a made-up claim.
  2. 2It also passes in a fixed model answer.
  3. 3The result is compared with the expected figure.
The rule now sits between two fakes and one check. Nothing in the middle reaches outside, so the test is quick and gives the same answer every time.

How do you refactor without breaking live claims?

  1. 1

    Write the safety net first

    Record what the messy code does today, odd cases included, as tests. If a later change moves that behaviour, a test fails.

  2. 2

    Pull out the rules

    Move the payout sum into a function with no side effects, and test it with made-up numbers.

  3. 3

    Pass in the outside world

    Give the function its database, model and mailer as arguments. Real ones go in the top layer; fakes go in the tests.

  4. 4

    Keep behaviour changes apart

    Fix bugs and change rules in their own saved steps (commits in version control), each with its own test, so a regression (a bug that a change brings back or creates) points to one change.

OpenAI's GPT-5 Codex prompting guide includes this rule in its sample instructions for the coding agent, and Anthropic's Claude Code guide says a check that comes back pass or fail lets the agent fix its own mistakes:

  • โ€œPreserve intended behavior and UX; gate or flag intentional changes and add tests when behavior shiftsโ€

    OpenAI, GPT-5 Codex prompting guide (sample instructions)

  • โ€œIf you give it something that comes back pass or fail, Claude can close that loop itself.โ€

    Anthropic, Claude Code best practices

Tip

Don't rewrite a live system from scratch. A rewrite has no safety net, and it is hard to review in one go. Refactor in small steps, with the tests green after each one.

How would you test a function that calls a model?

Put the model call behind one small function, a seam, that takes text and returns a label. Your tests pass in a fake that returns a fixed label, so the payout rules run quickly and need no model call.

  1. 1

    Unit tests use the fake

    They check your own code and run on every commit at no model cost.

  2. 2

    A fixed test list calls the real model

    It runs a fixed list of test questions with known good answers (an evaluation set). It costs money, so run it on a schedule or before a release.

  3. 3

    Score it over time

    Score the answers with rules, then track the score, so a model update that breaks one case shows up.

What does the interviewer want to hear?

A strong answer covers

  • A safety net of tests before any change.
  • Pure rules apart from the code that talks to the outside world.
  • Dependencies passed in, so tests can pass in fakes.
  • Small steps, one change per saved step (commit), tests after each.
  • The model call behind a seam, and the model judged separately.
  • A clear no to rewriting a live system in one go.

Common traps

  • Trap"Rewrite the whole thing from scratch, it is cleaner."

    BetterA rewrite has no safety net. Refactor in small steps, with tests after each one.

  • Trap"Mock everything and the tests are fine."

    BetterToo many stand-ins (mocks) hide real behaviour. Use a few fakes at the edges and keep the rules real.

  • Trap"We will add the tests once the refactor is done."

    BetterThen no one can tell which change broke it. Write the tests first.

Can you spot the hidden dependency?

Spot the hidden dependency

Which function is hardest to test as it stands?

Quick check

A claims team wants a test for the payout rule that runs in under a second. What should change first?

Can you answer these from memory?

Flash cards ยท tap a card to flip it

1 / 6

What will they ask next?

  1. Q485Write tests and evals for an LLM function.12 min
  2. Q401Re-engineering round: fix bugs in unfamiliar code.12 min
  3. Q402Learning round: pick up a new codebase or API fast.13 min
  4. Q482Write a minimal agent loop with tool dispatch.12 min
  5. Q400Build a small CLI tool.11 min

Last updated on 27 November 2026

Inheriting an AI codebase nobody wants to touch?

I design and build AI products and agents, including the code and tests behind them. Book a short call and tell me what you need.