这份配方帮助你在已有测试保护下完成一次行为不变的小重构:先确认测试全绿,再让 Gemini 提出拆分方案,把约 30 行的重复逻辑分成可独立审查、验证和撤销的变更单元。最终目标不是代码更短,而是公开接口和可观察行为不变,重复职责变得集中。
如果通过 Gemini Apps 导入代码文件夹,先核对模型实际收到了哪些文件。官方帮助提醒,大材料可能遗漏细节。Gemini 可以协助识别重复、生成差异和整理检查项,但生成代码仍要由你运行测试和审查。
通俗解释:绿色测试是重构的护栏
跳转到“通俗解释:绿色测试是重构的护栏”重构应改变代码内部结构,不改变调用者看到的结果。开始前的绿色测试记录了当前行为;每完成一个很小的结构调整,就重跑同一组测试。某一步变红时,问题便落在刚才那一个变更单元里,可以先撤回再分析。
测试全绿不代表所有行为都已覆盖。先检查边界值、错误分支、公开导出和返回对象形状是否在测试里;缺少关键测试时,先补测试并确认它描述的是现有约定,再进入重构。
最小示例
跳转到“最小示例”反例:
重构这个模块,消除重复并让代码更优雅。改写:
先不要改代码。根据现有测试列出不得改变的公开行为,再给出最多 3 个可独立验证的重构步骤。每次只给一个最小 diff;我运行 node --test并回传结果后,你再继续下一步。不要修改测试来让实现变绿。完整示例:合并两种配送报价的重复逻辑
跳转到“完整示例:合并两种配送报价的重复逻辑”起始材料
跳转到“起始材料”这是一个虚构的文具订单报价模块。金额单位都是“分”,避免示例引入浮点金额换算。项目使用 Node.js 24、ECMAScript modules,测试命令是 node --test。
paper-quotes/├── package.json├── src/│ └── quote.js└── test/ └── quote.test.jspackage.json:
{"type":"module"}重构前的 src/quote.js:
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 };}完整的 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, }, );});允许修改范围与不变量
跳转到“允许修改范围与不变量”- 只允许修改
src/quote.js;本轮把test/quote.test.js当作只读行为契约,不增加依赖,不改其他文件。 - 不得改变公开导出:仍然只有
quoteStandard(lines)与quoteExpress(lines)。 - 不得改变返回对象的 4 个字段:
subtotalCents、discountCents、shippingCents、totalCents。 - 小计达到或超过
10_000分时,折扣是向下取整的 10%;标准配送费为800分,快速配送费为1_800分。 - 空数组和非法行仍抛出
TypeError,错误消息仍能分别匹配non-empty array与invalid line values。
先运行 node --test。预期基线是 tests 7、pass 7、fail 0;如果基线不是绿色,不开始重构。
完整提示词
跳转到“完整提示词”把 src/quote.js、test/quote.test.js 和刚才的测试输出一起提供:
请协助规划一次行为不变的小重构。先分析,不要立即改代码,也不要执行命令。
[目标]消除 quoteStandard 与 quoteExpress 中的重复校验、小计、折扣和返回对象组装逻辑。
[允许修改]只修改 src/quote.js。test/quote.test.js 是只读行为契约。
[不得改变]- 公开导出仍然只有 quoteStandard(lines) 与 quoteExpress(lines);- 两个函数仍同步返回同样的 4 字段对象;- 满 10_000 分(包含边界)减去向下取整的 10%;- 配送费、异常类型和可匹配的错误消息不变;- 不增加依赖,不顺手格式化无关代码。
[工作顺序]1. 先复述当前公开行为,并逐条指向测试证据;2. 提出最多 3 个变更单元,每个单元说明目的、不变量和要重跑的命令;3. 等我确认后,只给第 1 个最小 diff;4. 我会运行 node --test 并粘贴结果;只有 7 项全绿后再给下一步;5. 最后给出完整 src/quote.js、最终验证清单和仍未由测试覆盖的风险;6. 不要声称命令已运行,不要删除、放宽或改写现有断言来制造绿色结果。
[基线]node --test:tests 7,pass 7,fail 0。
[文件]在这里粘贴 src/quote.js 与 test/quote.test.js。按小提交式变更单元应用
跳转到“按小提交式变更单元应用”预期方案可以分成 3 步。这里的“提交式”只描述变更大小:每一步都应能独立审查和撤销,不表示本页替你执行了 git commit。
- 抽出
calculateSubtotal(lines),集中非空校验、行值校验与小计计算;运行node --test,确认7/7通过。 - 抽出
calculateDiscount(subtotalCents),原样搬移>= 10_000与Math.floor;再次运行node --test,确认7/7通过。 - 抽出
buildQuote(lines, shippingCents),让两个公开函数只传入不同配送费;再次运行node --test,确认7/7通过。
每一步都先读 diff:测试文件应无变化,新 helper 不应导出,公开函数名和参数不应变化。某一步失败时,不继续叠加下一步。
预期产物:重构后的完整模块
跳转到“预期产物:重构后的完整模块”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);}重构后的完整 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, }, );});预期失败:重构悄悄改变了边界行为
跳转到“预期失败:重构悄悄改变了边界行为”下面这个差异看起来只是条件整理,却把“达到门槛”改成了“超过门槛”。这是故意构造的预期失败,不要保留:
function calculateDiscount(subtotalCents) { return subtotalCents >= 10_000 ? Math.floor(subtotalCents * 0.1) : 0; return subtotalCents > 10_000 ? Math.floor(subtotalCents * 0.1) : 0;}运行 node --test 后,预期结果是 tests 7、pass 6、fail 1。唯一失败项应是 express quote discounts the exact threshold:
actual: { subtotalCents: 10000, discountCents: 0, shippingCents: 1800, totalCents: 11800 }expected: { subtotalCents: 10000, discountCents: 1000, shippingCents: 1800, totalCents: 10800 }这项测试证明 10_000 分边界属于公开行为。把条件恢复为 >=,再运行同一命令,结果应回到 tests 7、pass 7、fail 0。不要通过修改期望值或删除边界测试来获得绿色结果。
算术复核
跳转到“算术复核”示例中的 4 个有效订单分别用正向计算与反算核对:
| 情形 | 正向计算 | 反算小计 |
|---|---|---|
| 标准配送,低于门槛 | 2_500 × 2 + 3_000 × 1 = 8_000;8_000 - 0 + 800 = 8_800 |
8_800 - 800 + 0 = 8_000 |
| 快速配送,恰好达到门槛 | 2_500 × 4 = 10_000;折扣 1_000;10_000 - 1_000 + 1_800 = 10_800 |
10_800 - 1_800 + 1_000 = 10_000 |
| 标准配送,超过门槛 | 6_000 × 2 = 12_000;折扣 1_200;12_000 - 1_200 + 800 = 11_600 |
11_600 - 800 + 1_200 = 12_000 |
| 标准配送,折扣需要向下取整 | 3_335 × 3 = 10_005;10_005 × 10% = 1_000.5,向下取整为 1_000;10_005 - 1_000 + 800 = 9_805 |
9_805 - 800 + 1_000 = 10_005 |
作者在撰写时把这些文件放入独立临时目录,使用 Node.js v24.14.1、ECMAScript modules 与 node --test 复核:基线、3 个变更单元和恢复后的最终版本均为 7 项通过;故意把 >= 改为 > 时为 6 项通过、1 项失败。本页没有替你运行练习仓库,因此 frontmatter 的 source-checked 只表示产品事实已核对,不表示代码已在你的环境中 run-tested。
验证清单
跳转到“验证清单”- 基线测试先达到
tests 7、pass 7、fail 0,并保存命令与输出; - 每个变更单元只承担一个结构目标,完成后立即重跑同一命令;
test/quote.test.js没有被删除、放宽或改写来迁就实现;- 模块仍然只导出两个公开函数,参数、异常和返回对象形状不变;
- 门槛以下、恰好等于门槛、门槛以上及向下取整 4 组金额都与逐项计算一致;
- 故意行为变化只让边界测试失败,恢复
>=后 7 项重新全绿; - diff 只包含授权文件,没有依赖、格式化或无关功能变化;
- 仓库若另有完整测试、类型检查或 lint,已按项目文档运行,或明确记录未运行项。
失败恢复与安全边界
跳转到“失败恢复与安全边界”- 基线不是绿色:先停下,记录当前分支、版本、环境和失败输出;不要把旧缺陷混进重构。
- 某一步变红:撤回刚才那个变更单元,确认测试恢复,再用失败差异缩小原因;不要继续叠加下一步。
- 模型修改测试:除非你明确批准补充缺失覆盖,否则拒绝测试改动;实现应满足原契约。
- 补丁过大:要求按“抽一个 helper、运行一次测试”的粒度拆开,保留每一步的 diff。
- 回答遗漏文件或边界:重新给出收到的文件清单,并要求把每项不变量指向源码或测试证据。
- 建议危险命令:不要执行删除、重置、强推或生产变更;先读命令、限定目标并取得授权。
- 真实仓库含敏感内容:不要上传密钥、客户数据、生产日志或私有依赖凭据;改用最小合成复现。
Google 明确提醒,用户要对使用 Gemini 生成的代码负责,代码也可能涉及开源许可。重构结果仍需经过测试、人工审查和适合项目风险的安全检查。
下一步:如果测试尚未稳定复现问题,先读《定位并修复一个 Bug》;如果还不清楚调用入口,读《理解一个代码库》;需要通用恢复路径时,查看《排错》。