Skip to content
Visual explainer 3h to learn 5 steps

Refactor and review AI-generated code safely

Define behaviour invariants before a refactor and review the generated code for correctness, complexity, accessibility and unintended changes.

By Invicly Tech, , in Prompt Engineering and Vibe Coding. About 9 minutes to read.

Topic 15 of 29

In short

A refactor changes the shape of code without changing what it does. Before you ask an assistant to refactor, write down the behaviour that must stay the same and get tests around it. Afterwards, read the diff for correctness, extra complexity, accessibility and changes you did not ask for.

Think of it like this: It is like rearranging a kitchen: the meals you can cook must be the same afterwards, and you check every drawer to see nothing went missing.

Explained simply

Refactoring means changing how code is organised without changing what it does. Users should notice nothing. That makes it risky for an assistant, because a result that looks tidy can quietly change behaviour.

So start with invariants: a short list of things that must stay true. For example, "formatPrice returns 12.50 for 12.5" or "an empty cart still shows the empty message". Make sure tests cover them, and run them before you begin to get a green baseline.

Fix the test scope before you ask for the refactor, and do not let the assistant change those tests. If the tests stay the same and still pass, you have real evidence. Also say which public interfaces must stay compatible, such as exported function names, props and URLs.

Then review the diff on your own. Is it correct? Is it simpler, or did it add layers for nothing? Are labels, focus and keyboard use still intact? Did anything change that you did not ask for?

Press Play on a diagram to walk through it one step at a time.

SequenceSafe refactor with an assistant
You
Assistant
Test suite
  1. 1Run tests on the current code (green baseline)
    You to Test suite: Run tests on the current code (green baseline)
  2. 2Send invariants, test scope and API to keep
    You to Assistant: Send invariants, test scope and API to keep
  3. 3Return a small refactor diff
    Assistant to You: Return a small refactor diff
  4. 4Rerun the same tests, unchanged
    You to Test suite: Rerun the same tests, unchanged
  5. 5Report pass or fail
    Test suite to You: Report pass or fail
  6. 6Ask for fixes or accept after reading the diff
    You to Assistant: Ask for fixes or accept after reading the diff
CompareWhat to check in generated code
Correct
  • Edge cases still handled
  • Errors still surface
  • Types still tight
Simple
  • No new abstraction for one use
  • No extra dependency
  • Fewer lines, not more
Inclusive and clean
  • Labels and focus kept
  • No unrelated renames
  • No deleted comments or tests
FlowRefactor in small safe steps
  1. 1
    Green baseline

    Run tests on current code

  2. 2
    One small step

    For example, extract one function

  3. 3
    Run tests

    Same tests, unchanged

  4. 4
    Read the diff

    Scope, complexity, accessibility

  5. 5
    Commit

    One step per commit

In depth

Writing behaviour invariants

An invariant is a sentence that can be checked. Good invariants describe inputs and outputs, error cases and edge cases. They do not describe the inside of the code, because the inside is what you are changing.

Write five to ten. If some are not yet covered by tests, add those tests first against the old code. A refactor on untested code is a guess. A refactor behind passing tests is an experiment you can undo.

  • Inputs and outputs
  • Error and empty cases
  • Ordering and rounding rules
  • Side effects such as saved data
  • Each one is checkable

Test scope and compatibility

Decide which tests are the judge. Tell the assistant they are read-only for this task. If a test must change, that is a behaviour change, not a refactor, and it needs a separate decision.

List the public interfaces that must stay stable. For a React component, that is its props. For a module, its exports. For an API, its routes and response shapes. Changing one of these breaks callers you may not have in front of you.

LayersWhat a refactor may and may not change
  1. 1
    Public interface

    Props, exports, routes: keep compatible

  2. 2
    Behaviour

    Outputs and errors: must not change

  3. 3
    Tests

    Read-only judge during the refactor

  4. 4
    Internal structure

    Free to change: names, helpers, file layout

Reviewing for complexity and accessibility

Generated code often adds abstractions: a helper used once, a config object, a wrapper component. Ask whether each one makes the next change easier. If not, ask for the plain version.

Check accessibility after any UI refactor. Buttons should stay buttons. Inputs need their labels. Focus should stay visible and move in a sensible order. Heading levels and alt text should not disappear. These details are easy for a tidy-up to drop, and tests rarely notice.

  • Does each new helper have two callers?
  • Still real buttons and labels?
  • Focus order unchanged?
  • No removed comments or checks

Reading the diff for surprises

Use git diff --stat to see which files changed, then read each hunk. Look for renamed files, deleted tests, changed config, new packages, loosened types such as any, and removed error handling. These are the usual signs of an unintended change.

If the diff is too big to read, the task was too big. Revert and ask for one small step at a time. A refactor you cannot read is not safe to merge.

MapUnintended changes to look for
Diff review
  • Files
    • Renamed or moved
    • Deleted tests
  • Types
    • any added
    • Optional chaining hiding errors
  • Config
    • Changed lint or tsconfig
    • New packages
  • Behaviour
    • Removed error handling
    • Changed defaults

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Write behaviour invariants~35m
  2. 2
    Fix the test scope first~35m
  3. 3
    Keep public interfaces compatible~35m
  4. 4
    Review for complexity and accessibility~35m
  5. 5
    Spot unintended changes in the diff~35m

Key points

  • Write invariants first: the behaviours, outputs and error cases that must not change.
  • Fix the test scope before refactoring, and do not let the assistant edit the tests it is judged by.
  • Keep public interfaces compatible: exported names, props, URLs and response shapes.
  • Review for complexity and accessibility, not only whether it runs.
  • Scan the whole diff for unintended changes such as renamed files or removed checks.

Key terms

Tap a card to flip it. 0/5 known

Examples

Extracting a price formatter

A component formats prices inline in three places. Step 1: list invariants (12.5 shows 12.50; 0 shows 0.00; negative values show a minus sign). Step 2: add tests for them on the old code and run them. Step 3: ask the assistant to extract one function named formatPrice in the same file, keeping the component props unchanged. Step 4: rerun the unchanged tests. Step 5: read the diff for extras.

text
Task: refactor PriceTag.tsx. Do not change behaviour.
Invariants: 12.5 -> "12.50"; 0 -> "0.00"; -3 -> "-3.00"
Tests: PriceTag.test.tsx is read-only.
Compatibility: keep the exported name and props.
Change: extract a formatPrice helper in the same file.
Output: minimal diff, no new packages.

Catching an unintended change

The refactor passes the tests, but the diff shows the Email input lost its label and the form now uses a div instead of a button for Submit. Step 1: spot it in the diff. Step 2: tell the assistant exactly which lines to restore. Step 3: add a test that finds the field by its label and the button by its role. Step 4: rerun everything. The new test now guards what the old tests missed.

ts
import { render, screen } from "@testing-library/react";
import { Form } from "./Form";

it("keeps the label and a real submit button", () => {
  render(<Form />);
  expect(screen.getByLabelText("Email")).toBeTruthy();
  expect(screen.getByRole("button", { name: "Submit" })).toBeTruthy();
});

Quick reference

  • Write 5 to 10 checkable invariants before you refactor.
  • Get a green test run on the old code first.
  • Treat the tests as read-only. A test change means behaviour changed.
  • Keep exports, props, routes and response shapes compatible.
  • Ask for one small step at a time and commit each one.
  • Check labels, real buttons, focus order and headings after UI changes.
  • Read git diff --stat, then every hunk, for renames, deleted tests and new packages.

Common mistakes

  • Letting the assistant rewrite the tests during the refactor, so green means nothing.
  • Merging a large diff after skimming only the first file.
  • Accepting a tidy-looking abstraction that adds complexity for one caller.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is a behaviour invariant?

Question 2

2Why should tests be read-only during a refactor?

Question 3

3Which is a sign of added complexity?

Question 4

4A refactored form passes all tests but its inputs have no labels. What does this show?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write five invariants for a function that formats a date as DD/MM/YYYY.

  2. Exercise 2medium

    Write a refactor prompt that protects tests and the public interface.

  3. Exercise 3hard

    Review this diff summary and list what you would reject: 6 files changed, formatDate renamed to fmt, a test deleted, package date-fns added, tsconfig strict set to false.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I refactor code that has no tests?
Add tests for the current behaviour first. Without them you cannot tell a safe change from a risky one.
How big should one refactor step be?
Small enough to read the whole diff in a few minutes. One function or one component per step is a good size.
Does passing lint and tests mean the diff is safe?
No. They catch many mistakes, but not unrelated changes, extra complexity or lost accessibility. You still read the diff.

Go deeper

ShareXLinkedInWhatsApp