這份配方幫助你在已有測試保護下完成一次行為不變的小重構:先確認測試全綠,再讓 Gemini 提出拆分方案,把約 30 行的重複邏輯分成可獨立審查、驗證和撤銷的變更單元。最終目標不是程式碼更短,而是公開介面和可觀察行為不變,重複職責變得集中。
如果通過 Gemini Apps 匯入程式碼資料夾,先核對模型實際收到了哪些檔案。官方幫助提醒,大材料可能遺漏細節。Gemini 可以協助識別重複、生成差異和整理檢查項,但生成程式碼仍要由你執行測試和審查。
通俗解釋:綠色測試是重構的護欄
Section titled “通俗解釋:綠色測試是重構的護欄”重構應改變程式碼內部結構,不改變呼叫者看到的結果。開始前的綠色測試記錄了當前行為;每完成一個很小的結構調整,就重跑同一組測試。某一步變紅時,問題便落在剛才那一個變更單元裡,可以先撤回再分析。
測試全綠不代表所有行為都已覆蓋。先檢查邊界值、錯誤分支、公開匯出和返回物件形狀是否在測試裡;缺少關鍵測試時,先補測試並確認它描述的是現有約定,再進入重構。
反例:
重構這個模組,消除重複並讓程式碼更優雅。改寫:
先不要改程式碼。根據現有測試列出不得改變的公開行為,再給出最多 3 個可獨立驗證的重構步驟。每次只給一個最小 diff;我執行 node --test並回傳結果後,你再繼續下一步。不要修改測試來讓實現變綠。完整示例:合併兩種配送報價的重複邏輯
Section titled “完整示例:合併兩種配送報價的重複邏輯”這是一個虛構的文具訂單報價模組。金額單位都是「分」,避免示例引入浮點金額換算。專案使用 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, }, );});允許修改範圍與不變數
Section titled “允許修改範圍與不變數”- 只允許修改
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。按小提交式變更單元應用
Section titled “按小提交式變更單元應用”預期方案可以分成 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 不應匯出,公開函式名和引數不應變化。某一步失敗時,不繼續疊加下一步。
預期產物:重構後的完整模組
Section titled “預期產物:重構後的完整模組”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, }, );});預期失敗:重構悄悄改變了邊界行為
Section titled “預期失敗:重構悄悄改變了邊界行為”下面這個差異看起來只是條件整理,卻把「達到門檻」改成了「超過門檻」。這是故意構造的預期失敗,不要保留:
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,已按專案文件執行,或明確記錄未執行項。
失敗恢復與安全邊界
Section titled “失敗恢復與安全邊界”- 基線不是綠色:先停下,記錄當前分支、版本、環境和失敗輸出;不要把舊缺陷混進重構。
- 某一步變紅:撤回剛才那個變更單元,確認測試恢復,再用失敗差異縮小原因;不要繼續疊加下一步。
- 模型修改測試:除非你明確批准補充缺失覆蓋,否則拒絕測試改動;實現應滿足原契約。
- 補丁過大:要求按「抽一個 helper、執行一次測試」的粒度拆開,保留每一步的 diff。
- 回答遺漏檔案或邊界:重新給出收到的檔案清單,並要求把每項不變數指向原始碼或測試證據。
- 建議危險命令:不要執行刪除、重置、強推或生產變更;先讀命令、限定目標並取得授權。
- 真實倉庫含敏感內容:不要上傳金鑰、客戶資料、生產日誌或私有依賴憑據;改用最小合成復現。
Google 明確提醒,使用者要對使用 Gemini 生成的程式碼負責,程式碼也可能涉及開源許可。重構結果仍需經過測試、人工審查和適合專案風險的安全檢查。
下一步:如果測試尚未穩定復現問題,先讀《定位並修復一個 Bug》;如果還不清楚呼叫入口,讀《理解一個程式碼庫》;需要通用恢復路徑時,檢視《排錯》。