# 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.

AI and LLM interview question Q484, Coding and practical. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/refactor-messy-code-into-testable-code

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

- **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:

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

*Diagram, After: the rule is a plain function: 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.*
1. The test passes in a made-up claim.
2. It also passes in a fixed model answer.
3. The 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." Better: A rewrite has no safety net. Refactor in small steps, with tests after each one.
- Trap: "Mock everything and the tests are fine." Better: Too 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." Better: Then 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?

A. def payout_for(amount, limit, excess): return max(0, min(amount, limit) - excess)
B. def review_claim(claim_id): row = db.load(claim_id); mailer.send(row.email, row.amount)
C. def round_money(x): return round(x, 2)
D. def is_policy_active(p): return p.start <= p.today <= p.end

**Answer:** B. It loads from a live database and sends mail inside the function. Pass the database and mailer in, and keep the rule apart so a test can reach it.

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

A. Run the test against the live database
B. Pull the payout rule into a function and pass in plain numbers
C. Switch to a faster model
D. Add more log lines to the email step

**Answer:** B. A plain function with numbers in and a number out runs quickly and needs no server. The rest of the code can stay as it is for now.

## Can you answer these from memory?

**Flash cards**

- **What is refactoring?** Changing how code is arranged without changing what it does.
- **What makes code hard to test?** Rules tangled with calls to a database, a model or email.
- **What is a pure function?** Same inputs, same output, and no calls to anything outside.
- **What is dependency injection?** The caller passes in the services a function needs.
- **Why write tests first?** They are a safety net: they show when behaviour has changed.
- **How do you test a model call?** Put it behind a seam, test with a fake, judge the model separately.

## Likely follow-up questions

- Q485 Write tests and evals for an LLM function. https://designervenkat.online/interview/ai/write-tests-and-evals-for-an-llm-function
- Q401 Re-engineering round: fix bugs in unfamiliar code. https://designervenkat.online/interview/ai/re-engineering-round-fix-bugs-in-unfamiliar-code
- Q402 Learning round: pick up a new codebase or API fast. https://designervenkat.online/interview/ai/learning-round-pick-up-a-new-codebase-or-api-fast
- Q482 Write a minimal agent loop with tool dispatch. https://designervenkat.online/interview/ai/write-a-minimal-agent-loop-with-tool-dispatch
- Q400 Build a small CLI tool. https://designervenkat.online/interview/ai/build-a-small-cli-tool
