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.
Messy code is often one long function that does several jobs at once. It loads a claim from the database, asks a model whether it looks like fraud, works out the payout, and emails the customer. To test the payout rule, you have to run all four, which means a live database, a paid model call and a real inbox. Without a test, a wrong rule can ship without anyone noticing.
I start with a safety net. Before I change anything, I write tests that record what the code does today, odd cases included. Then I move in small steps and run the tests after each one, so each change is small enough to review in one sitting. First I pull the payout rule into a plain function that takes numbers and returns a number. Then I pass the database, the model and the mailer in as arguments, so the caller decides which ones are real.
The result is a thin top layer that wires the real systems together, and a core that a test can reach with fake inputs. Behaviour must not change by accident. A new business rule is a separate change with its own test. For a claims team, the payout rule can then be checked quickly with no database, and a mistake in it shows up as a red test before it reaches a customer. Tests that pass before and after give real evidence that a refactor kept the behaviour, though they do not prove the code is bug-free.
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.
# 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
- 1The test passes in a made-up claim.
- 2It also passes in a fixed model answer.
- 3The result is compared with the expected figure.
How do you refactor without breaking live claims?
- 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
Pull out the rules
Move the payout sum into a function with no side effects, and test it with made-up numbers.
- 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
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
Unit tests use the fake
They check your own code and run on every commit at no model cost.
- 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
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
What will they ask next?
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.