コンテンツにスキップ

メニュー

プレイブック

テストを安全網にして小さなリファクタリングを行う

テストがすべて通る基準状態を確保してから、重複ロジックを個別に検証できる小さな変更に分割します。

分で読めます
25
レベル
上級
最終確認日

このプレイブックでは、既存のテストを安全網にして、動作を維持したまま小規模なリファクタリングを行います。まず、すべてのテストが通ることを確認します。次に、約 30 行の重複ロジックを、個別にレビュー、検証、取り消しできる変更に分割する方法を Gemini に提案させます。目標はコードを短くすることではなく、公開インターフェースと観察可能な動作を変えずに、重複した責務を一か所にまとめることです。

Gemini Apps からコードフォルダを読み込む場合は、モデルが実際に受け取ったファイルを最初に確認します。公式ヘルプには、大量の入力では詳細が見落とされる場合があると記載されています。Gemini は重複の特定、差分の生成、確認項目の整理に役立ちますが、テストの実行と生成コードのレビューは引き続き自分で行う必要があります。

平易な説明:通るテストはリファクタリングのガードレール

Section titled “平易な説明:通るテストはリファクタリングのガードレール”

リファクタリングでは、呼び出し側から見える動作を変えずに、コードの内部構造を変更します。作業開始前にテストが通った記録は、現在の動作を示す基準になります。構造を少し調整するたびに、同じテストを再実行します。ある手順でテストが失敗した場合、問題は直前の変更に限定されるため、調査する前にその変更を取り消せます。

テストが通っていても、すべての動作が網羅されているとは限りません。まず、境界値、エラー経路、公開エクスポート、返却オブジェクトの形状がテストされているか確認します。重要なテストが不足している場合は先に追加し、リファクタリングを始める前に、そのテストが既存の契約を記述していることを確認してください。

不十分なプロンプト:

このモジュールをリファクタリングして重複をなくし、コードをより洗練してください。

改善したプロンプト:

まだコードを変更しないでください。既存のテストに基づいて、変更してはならない公開動作を
列挙してから、個別に検証できるリファクタリング手順を 3 つ以内で提案してください。
一度に提示するのは最小限の diff 1 つだけにしてください。私が node --test を実行して
結果を送った後にだけ、次の手順へ進んでください。実装を通すためにテストを変更しないでください。

完全な例:2 種類の配送見積もりにある重複ロジックをまとめる

Section titled “完全な例:2 種類の配送見積もりにある重複ロジックをまとめる”

これは、文房具の注文に使う架空の見積もりモジュールです。例で浮動小数点による通貨換算を避けるため、すべての金額をセント単位で扱います。プロジェクトでは Node.js 24 と ECMAScript modules を使用し、テストコマンドは node --test です。

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

package.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 を貼り付けます。

コミット相当の小さな変更単位で作業する

Section titled “コミット相当の小さな変更単位で作業する”

想定される計画は 3 つの手順に分けられます。ここで「コミット相当」とは、各変更の大きさだけを表します。各手順を個別にレビューして取り消せるようにするという意味であり、このページが git commit を実行したという意味ではありません。

  1. calculateSubtotal(lines) を抽出して、空でないことの確認、明細の検証、小計計算を一か所にまとめます。node --test を実行し、7/7 件のテストが通ることを確認します。
  2. calculateDiscount(subtotalCents) を抽出し、>= 10_000 と Math.floor を変更せずに移動します。もう一度 node --test を実行し、7/7 件のテストが通ることを確認します。
  3. buildQuote(lines, shippingCents) を抽出し、2 つの公開関数が異なる配送料だけを渡すようにします。もう一度 node --test を実行し、7/7 件のテストが通ることを確認します。

各手順の前に差分を読みます。テストファイルに変更がなく、新しいヘルパーがエクスポートされておらず、公開関数の名前と引数が変わっていないことを確認してください。ある手順が失敗した場合、その上に次の手順を重ねないでください。

期待する出力:リファクタリング後の完全なモジュール

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 が削除、緩和、書き換えされていないことを確認します。
  • モジュールが引き続き 2 つの公開関数だけをエクスポートし、その引数、例外、返却オブジェクトの形状が変わっていないことを確認します。
  • しきい値未満、しきい値と同額、しきい値超過、切り捨てが必要な場合という 4 組の金額が、項目ごとの計算と一致することを確認します。
  • 意図的な動作変更によって境界テストだけが失敗し、>= に戻すと 7 件のテストがすべて再び通ることを確認します。
  • 差分に許可されたファイルだけが含まれ、依存関係、整形、無関係な機能の変更がないことを確認します。
  • リポジトリに完全なテストスイート、型チェック、lint がある場合は、プロジェクトの文書に従って実行するか、実行しなかったものを明記します。

障害からの復旧と安全上の境界

Section titled “障害からの復旧と安全上の境界”
  • 基準状態でテストが通らない:作業を止めます。現在のブランチ、バージョン、環境、失敗出力を記録します。既存の不具合をリファクタリングに混ぜないでください。
  • ある手順でテストが失敗する:直前の変更単位を取り消し、テストが復旧することを確認してから、失敗時の差分を使って原因を絞り込みます。その上に次の手順を重ねないでください。
  • モデルがテストを変更する:不足しているテスト範囲の追加を明示的に承認した場合を除き、テストの変更を却下します。実装が既存の契約を満たす必要があります。
  • パッチが大きすぎる:「ヘルパーを一つ抽出し、テストを一度実行する」という粒度に分割するよう求め、各手順の差分を保持します。
  • 回答にファイルまたは境界が含まれていない:受け取ったファイルをもう一度列挙し、すべての不変条件をソースまたはテストの根拠と結び付けるよう求めます。
  • 危険なコマンドを提案された:削除、リセット、強制プッシュ、本番環境の変更を実行しないでください。まずコマンドを読み、対象を限定し、承認を得ます。
  • 実際のリポジトリに機密情報が含まれる:キー、顧客データ、本番ログ、非公開依存関係の認証情報をアップロードしないでください。代わりに最小限の架空の再現例を使います。

Google は、Gemini で生成されたコードの責任はユーザーにあり、そのコードがオープンソースライセンスの対象となる場合があると明記しています。リファクタリング結果にも、テスト、人によるレビュー、プロジェクトのリスク水準に応じたセキュリティ確認が必要です。

次の手順:テストでまだ問題を確実に再現できない場合は、不具合を特定して修正するを参照してください。入口がまだ不明な場合は、コードベースを理解するを参照してください。一般的な復旧手順については、トラブルシューティングを参照してください。