Skip to content

Menu

Playbooks

Perform a small refactor with tests as a safety net

Lock in a green baseline, then split duplicated logic into small, independently verifiable changes.

min read
25
Level
Advanced
Last verified

This playbook helps you perform a small, behavior-preserving refactor with existing tests as a safety net. First, confirm that every test is green. Then ask Gemini to propose how to split roughly 30 lines of duplicated logic into changes that can each be reviewed, verified, and reverted independently. The goal is not shorter code, but unchanged public interfaces and observable behavior with duplicated responsibilities consolidated in one place.

If you import a code folder through Gemini Apps, first verify which files the model actually received. The official help documentation warns that details may be missed in large inputs. Gemini can help identify duplication, generate diffs, and organize checks, but you still need to run the tests and review any generated code.

In plain English: Green tests are the guardrails for refactoring

Section titled “In plain English: Green tests are the guardrails for refactoring”

Refactoring should change the code’s internal structure without changing what callers observe. A green test run before you begin records the current behavior. After each small structural adjustment, rerun the same tests. If a step turns them red, the problem is confined to the change you just made, so you can revert it before investigating.

Green tests do not mean every behavior is covered. First check whether the tests cover boundary values, error paths, public exports, and the shape of returned objects. If a critical test is missing, add it first and confirm that it describes the existing contract before you start refactoring.

Weak prompt:

Refactor this module to eliminate duplication and make the code more elegant.

Better prompt:

Do not change the code yet. Based on the existing tests, list the public behaviors
that must not change, then propose no more than 3 independently verifiable
refactoring steps. Provide only one minimal diff at a time. Continue to the next
step only after I run node --test and send you the result. Do not modify the tests
to make the implementation pass.

Complete example: Consolidate duplicated logic in two shipping quotes

Section titled “Complete example: Consolidate duplicated logic in two shipping quotes”

This is a fictional quote module for stationery orders. All monetary amounts are in cents, avoiding floating-point currency conversion in the example. The project uses Node.js 24 and ECMAScript modules, and its test command is node --test.

paper-quotes/
├── package.json
├── src/
│ └── quote.js
└── test/
└── quote.test.js

package.json:

{"type":"module"}

src/quote.js before the refactor:

export function quoteStandard(lines) {
if (!Array.isArray(lines) || lines.length === 0) {
throw new TypeError('lines must be a non-empty array');
}
const subtotalCents = lines.reduce((sum, line) => {
if (!Number.isInteger(line.unitPriceCents) || line.unitPriceCents < 0 ||
!Number.isInteger(line.quantity) || line.quantity < 1) {
throw new TypeError('invalid line values');
}
return sum + line.unitPriceCents * line.quantity;
}, 0);
const discountCents = subtotalCents >= 10_000 ? Math.floor(subtotalCents * 0.1) : 0;
const shippingCents = 800;
return { subtotalCents, discountCents, shippingCents,
totalCents: subtotalCents - discountCents + shippingCents };
}
export function quoteExpress(lines) {
if (!Array.isArray(lines) || lines.length === 0) {
throw new TypeError('lines must be a non-empty array');
}
const subtotalCents = lines.reduce((sum, line) => {
if (!Number.isInteger(line.unitPriceCents) || line.unitPriceCents < 0 ||
!Number.isInteger(line.quantity) || line.quantity < 1) {
throw new TypeError('invalid line values');
}
return sum + line.unitPriceCents * line.quantity;
}, 0);
const discountCents = subtotalCents >= 10_000 ? Math.floor(subtotalCents * 0.1) : 0;
const shippingCents = 1_800;
return { subtotalCents, discountCents, shippingCents,
totalCents: subtotalCents - discountCents + shippingCents };
}

The complete test/quote.test.js:

import test from 'node:test';
import assert from 'node:assert/strict';
import * as quote from '../src/quote.js';
const { quoteExpress, quoteStandard } = quote;
test('keeps the public exports stable', () => {
assert.deepEqual(Object.keys(quote).sort(), ['quoteExpress', 'quoteStandard']);
});
test('standard quote below discount threshold', () => {
const lines = [
{ unitPriceCents: 2_500, quantity: 2 },
{ unitPriceCents: 3_000, quantity: 1 },
];
assert.deepEqual(quoteStandard(lines), {
subtotalCents: 8_000,
discountCents: 0,
shippingCents: 800,
totalCents: 8_800,
});
});
test('express quote discounts the exact threshold', () => {
assert.deepEqual(
quoteExpress([{ unitPriceCents: 2_500, quantity: 4 }]),
{
subtotalCents: 10_000,
discountCents: 1_000,
shippingCents: 1_800,
totalCents: 10_800,
},
);
});
test('standard quote above discount threshold', () => {
assert.deepEqual(
quoteStandard([{ unitPriceCents: 6_000, quantity: 2 }]),
{
subtotalCents: 12_000,
discountCents: 1_200,
shippingCents: 800,
totalCents: 11_600,
},
);
});
test('rejects an empty order through either public function', () => {
const expected = {
name: 'TypeError',
message: 'lines must be a non-empty array',
};
assert.throws(() => quoteStandard([]), expected);
assert.throws(() => quoteExpress([]), expected);
});
test('rejects invalid line values through either public function', () => {
const invalidCases = [
[{ unitPriceCents: -1, quantity: 1 }],
[{ unitPriceCents: 1.5, quantity: 1 }],
[{ unitPriceCents: 100, quantity: 0 }],
[{ unitPriceCents: 100, quantity: 1.5 }],
];
const expected = { name: 'TypeError', message: 'invalid line values' };
for (const invalid of invalidCases) {
assert.throws(() => quoteStandard(invalid), expected);
assert.throws(() => quoteExpress(invalid), expected);
}
});
test('standard quote floors a fractional discount', () => {
assert.deepEqual(
quoteStandard([{ unitPriceCents: 3_335, quantity: 3 }]),
{
subtotalCents: 10_005,
discountCents: 1_000,
shippingCents: 800,
totalCents: 9_805,
},
);
});
  • You may modify only src/quote.js. For this pass, treat test/quote.test.js as a read-only behavioral contract. Do not add dependencies or change any other files.
  • Do not change the public exports: they must remain exactly quoteStandard(lines) and quoteExpress(lines).
  • Do not change the 4 fields in the returned object: subtotalCents, discountCents, shippingCents, and totalCents.
  • When the subtotal reaches or exceeds 10_000 cents, the discount is 10%, rounded down. Standard shipping costs 800 cents, and express shipping costs 1_800 cents.
  • Both public functions must still throw a TypeError for an empty array or invalid line items, with error messages that continue to match non-empty array and invalid line values, respectively.

Run node --test first. The expected baseline is tests 7, pass 7, and fail 0. If the baseline is not green, do not start the refactor.

Provide src/quote.js, test/quote.test.js, and the test output from the baseline run:

Help me plan a small, behavior-preserving refactor. Analyze first. Do not change
the code yet, and do not run any commands.
[Goal]
Eliminate the duplicated validation, subtotal calculation, discount calculation,
and returned-object assembly in quoteStandard and quoteExpress.
[Allowed changes]
Modify only src/quote.js. test/quote.test.js is a read-only behavioral contract.
[Must not change]
- The only public exports must remain quoteStandard(lines) and quoteExpress(lines).
- Both functions must continue to synchronously return the same 4-field object.
- At 10_000 cents or more, including the boundary, subtract 10%, rounding the discount down.
- Shipping fees, exception types, and the error-message text matched by the tests must not change.
- Do not add dependencies or opportunistically format unrelated code.
[Workflow]
1. First restate the current public behavior and point to the test evidence for
each item.
2. Propose no more than 3 change units. For each, state its purpose, invariants,
and the command to rerun.
3. Wait for my confirmation, then provide only the minimal diff for step 1.
4. I will run node --test and paste the result. Continue only after all 7 tests
are green.
5. At the end, provide the complete src/quote.js, a final verification checklist,
and any risks that the tests still do not cover.
6. Do not claim that you ran commands. Do not delete, weaken, or rewrite existing
assertions to manufacture a green result.
[Baseline]
node --test: tests 7, pass 7, fail 0.
[Files]
Paste src/quote.js and test/quote.test.js here.

Apply the work as small, commit-sized change units

Section titled “Apply the work as small, commit-sized change units”

The expected plan can be divided into 3 steps. Here, “commit-sized” describes only the size of each change: every step should be independently reviewable and reversible. It does not mean this page ran git commit for you.

  1. Extract calculateSubtotal(lines) to centralize the non-empty check, line-item validation, and subtotal calculation. Run node --test and confirm that 7/7 tests pass.
  2. Extract calculateDiscount(subtotalCents), moving >= 10_000 and Math.floor without alteration. Run node --test again and confirm that 7/7 tests pass.
  3. Extract buildQuote(lines, shippingCents) so the two public functions pass only their different shipping fees. Run node --test again and confirm that 7/7 tests pass.

Read the diff before each step. The test file should be unchanged, the new helpers should not be exported, and the public function names and parameters should remain unchanged. If a step fails, do not stack the next step on top of it.

Expected output: Complete refactored module

Section titled “Expected output: Complete refactored module”
function calculateSubtotal(lines) {
if (!Array.isArray(lines) || lines.length === 0) {
throw new TypeError('lines must be a non-empty array');
}
return lines.reduce((sum, line) => {
if (!Number.isInteger(line.unitPriceCents) || line.unitPriceCents < 0 ||
!Number.isInteger(line.quantity) || line.quantity < 1) {
throw new TypeError('invalid line values');
}
return sum + line.unitPriceCents * line.quantity;
}, 0);
}
function calculateDiscount(subtotalCents) {
return subtotalCents >= 10_000 ? Math.floor(subtotalCents * 0.1) : 0;
}
function buildQuote(lines, shippingCents) {
const subtotalCents = calculateSubtotal(lines);
const discountCents = calculateDiscount(subtotalCents);
return { subtotalCents, discountCents, shippingCents,
totalCents: subtotalCents - discountCents + shippingCents };
}
export function quoteStandard(lines) {
return buildQuote(lines, 800);
}
export function quoteExpress(lines) {
return buildQuote(lines, 1_800);
}

The complete test/quote.test.js after the refactor is identical to the baseline. Do not make the implementation green by changing the tests:

import test from 'node:test';
import assert from 'node:assert/strict';
import * as quote from '../src/quote.js';
const { quoteExpress, quoteStandard } = quote;
test('keeps the public exports stable', () => {
assert.deepEqual(Object.keys(quote).sort(), ['quoteExpress', 'quoteStandard']);
});
test('standard quote below discount threshold', () => {
const lines = [
{ unitPriceCents: 2_500, quantity: 2 },
{ unitPriceCents: 3_000, quantity: 1 },
];
assert.deepEqual(quoteStandard(lines), {
subtotalCents: 8_000,
discountCents: 0,
shippingCents: 800,
totalCents: 8_800,
});
});
test('express quote discounts the exact threshold', () => {
assert.deepEqual(
quoteExpress([{ unitPriceCents: 2_500, quantity: 4 }]),
{
subtotalCents: 10_000,
discountCents: 1_000,
shippingCents: 1_800,
totalCents: 10_800,
},
);
});
test('standard quote above discount threshold', () => {
assert.deepEqual(
quoteStandard([{ unitPriceCents: 6_000, quantity: 2 }]),
{
subtotalCents: 12_000,
discountCents: 1_200,
shippingCents: 800,
totalCents: 11_600,
},
);
});
test('rejects an empty order through either public function', () => {
const expected = {
name: 'TypeError',
message: 'lines must be a non-empty array',
};
assert.throws(() => quoteStandard([]), expected);
assert.throws(() => quoteExpress([]), expected);
});
test('rejects invalid line values through either public function', () => {
const invalidCases = [
[{ unitPriceCents: -1, quantity: 1 }],
[{ unitPriceCents: 1.5, quantity: 1 }],
[{ unitPriceCents: 100, quantity: 0 }],
[{ unitPriceCents: 100, quantity: 1.5 }],
];
const expected = { name: 'TypeError', message: 'invalid line values' };
for (const invalid of invalidCases) {
assert.throws(() => quoteStandard(invalid), expected);
assert.throws(() => quoteExpress(invalid), expected);
}
});
test('standard quote floors a fractional discount', () => {
assert.deepEqual(
quoteStandard([{ unitPriceCents: 3_335, quantity: 3 }]),
{
subtotalCents: 10_005,
discountCents: 1_000,
shippingCents: 800,
totalCents: 9_805,
},
);
});

Expected failure: The refactor silently changes boundary behavior

Section titled “Expected failure: The refactor silently changes boundary behavior”

The following diff may look like a simple cleanup of the condition, but it changes “reaches the threshold” to “exceeds the threshold.” This is an intentionally constructed expected failure. Do not keep it:

function calculateDiscount(subtotalCents) {
return subtotalCents >= 10_000 ? Math.floor(subtotalCents * 0.1) : 0;
return subtotalCents > 10_000 ? Math.floor(subtotalCents * 0.1) : 0;
}

After you run node --test, the expected result is tests 7, pass 6, and fail 1. The only failing test should be express quote discounts the exact threshold:

actual: { subtotalCents: 10000, discountCents: 0,
shippingCents: 1800, totalCents: 11800 }
expected: { subtotalCents: 10000, discountCents: 1000,
shippingCents: 1800, totalCents: 10800 }

This test proves that the 10_000-cent boundary is part of the public behavior. Restore the condition to >= and rerun the same command. The result should return to tests 7, pass 7, and fail 0. Do not obtain a green result by changing the expected value or deleting the boundary test.

For each of the 4 valid orders in the example, verify the forward calculation and reverse calculation:

Scenario Forward calculation Reverse subtotal calculation
Standard shipping, below the threshold 2_500 × 2 + 3_000 × 1 = 8_000; 8_000 - 0 + 800 = 8_800 8_800 - 800 + 0 = 8_000
Express shipping, exactly at the threshold 2_500 × 4 = 10_000; discount 1_000; 10_000 - 1_000 + 1_800 = 10_800 10_800 - 1_800 + 1_000 = 10_000
Standard shipping, above the threshold 6_000 × 2 = 12_000; discount 1_200; 12_000 - 1_200 + 800 = 11_600 11_600 - 800 + 1_200 = 12_000
Standard shipping, with a discount that must be rounded down 3_335 × 3 = 10_005; 10_005 × 10% = 1_000.5, rounded down to 1_000; 10_005 - 1_000 + 800 = 9_805 9_805 - 800 + 1_000 = 10_005

While writing this page, the author placed these files in an isolated temporary directory and verified them with Node.js v24.14.1, ECMAScript modules, and node --test. The baseline, all 3 change units, and the restored final version each passed all 7 tests. Intentionally changing >= to > produced 6 passing tests and 1 failure. This page did not run the exercise repository for you, so the source-checked value in the frontmatter means only that the product facts were verified, not that the code is run-tested in your environment.

  • First get the baseline to tests 7, pass 7, and fail 0, and save the command and its output.
  • Give each change unit only one structural goal, and rerun the same command immediately after completing it.
  • Confirm that test/quote.test.js was not deleted, weakened, or rewritten to accommodate the implementation.
  • Confirm that the module still exports only two public functions and that their parameters, exceptions, and returned-object shape are unchanged.
  • Confirm that the 4 sets of amounts—below the threshold, exactly at it, above it, and requiring rounding down—match the itemized calculations.
  • Confirm that the intentional behavior change breaks only the boundary test and that restoring >= returns all 7 tests to green.
  • Confirm that the diff contains only authorized files, with no dependency changes, formatting changes, or unrelated features.
  • If the repository has a full test suite, type checks, or linting, run them as documented by the project or explicitly record what you did not run.
  • The baseline is not green: Stop. Record the current branch, version, environment, and failure output. Do not mix a preexisting defect into the refactor.
  • A step turns red: Revert the change unit you just made, confirm that the tests recover, then use the failure diff to narrow down the cause. Do not stack the next step on top of it.
  • The model changes the tests: Reject test changes unless you explicitly approved adding missing coverage. The implementation should satisfy the existing contract.
  • The patch is too large: Ask for it to be split at the granularity of “extract one helper, run the tests once,” and preserve the diff from each step.
  • The response omits files or boundaries: List the files received again and ask for every invariant to be tied to evidence in the source or tests.
  • A dangerous command is suggested: Do not run deletions, resets, force pushes, or production changes. Read the command first, constrain its target, and obtain authorization.
  • The real repository contains sensitive material: Do not upload keys, customer data, production logs, or credentials for private dependencies. Use a minimal synthetic reproduction instead.

Google explicitly warns that users are responsible for code generated with Gemini and that the code may be subject to open source licenses. The refactoring result still needs tests, human review, and security checks appropriate to the project’s risk level.

Next step: If the tests do not yet reproduce the problem reliably, read Locate and fix a bug. If the entry point is still unclear, read Understand a codebase. For a general recovery path, see Troubleshooting.