jpskill.com
🛠️ 開発・MCP コミュニティ

refactoring

コードの品質改善や構造変更を、小さなステップでテストを繰り返しながら安全に進め、リファクタリング、整理、抽出、改名、簡素化などの要望に対応し、コードの匂いを解消するSkill。

📜 元の英語説明(参考)

Systematic refactoring with small-step discipline. Use when user says 'refactor', 'clean up', 'restructure', 'extract', 'rename', 'simplify', or mentions code smells. Enforces one change → test → commit cycle. For structural improvements, NOT style/formatting (use /lint). NOT for adding features or fixing bugs.

🇯🇵 日本人クリエイター向け解説

一言でいうと

コードの品質改善や構造変更を、小さなステップでテストを繰り返しながら安全に進め、リファクタリング、整理、抽出、改名、簡素化などの要望に対応し、コードの匂いを解消するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o refactoring.zip https://jpskill.com/download/17230.zip && unzip -o refactoring.zip && rm refactoring.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17230.zip -OutFile "$d\refactoring.zip"; Expand-Archive "$d\refactoring.zip" -DestinationPath $d -Force; ri "$d\refactoring.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して refactoring.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → refactoring フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

リファクタリング

振る舞いを変更せずにコード構造を改善します。一度に小さなステップで行います。

鉄の掟: 1つのリファクタリング → テスト → コミット。変更をまとめて行わないでください。

使うべき時

以下の順に答えてください。最初に一致した時点で止めてください。

  1. ユーザーが「リファクタリング」、「整理」、「再構築」と言った場合 → このスキルを使用
  2. ユーザーが「抽出」、「リネーム」、「単純化」を求めた場合 → このスキルを使用
  3. コードの臭い(code smell)が特定された場合 → このスキルを使用
  4. ユーザーが機能追加またはバグ修正を求めている場合 → スキップ(tdd-enforcerを使用)
  5. ユーザーがフォーマット/スタイルの修正を求めている場合 → スキップ(/lintを使用)

コードの臭い(一般的なトリガー):

  • 重複したコード(同じロジックが複数の場所にある)
  • 長い関数(30行以上、処理が多すぎる)
  • マジックナンバー/文字列(説明のないリテラル)
  • 深いネスト(3レベルを超えるインデント)
  • デッドコード(未使用の関数、到達不能な分岐)
  • 不適切な命名(何をするのか不明確)

フェーズ1:評価

これは本当にリファクタリングですか?

ユーザーの意図 アクション
「これをよりきれいにしたい」 ✓ リファクタリング
「バリデーションを追加したい」 ✗ 新しい振る舞い → tdd-enforcer
「このバグを修正したい」 ✗ バグ修正 → tdd-enforcer または systematic-debugger
「このコードをフォーマットしたい」 ✗ スタイル → /lint

リファクタリングでない場合: 説明し、正しいアプローチを提案してください。


フェーズ2:保護

コードにテストはありますか?

カバレッジ アクション
十分なテストがある フェーズ3へスキップ
部分的なカバレッジ テストされていない部分に対する特性化テストを追加
テストがない まず特性化テストを追加

特性化テスト

リファクタリング前に現在の振る舞いをキャプチャします。

// 特性化テスト - 実際の振る舞いをキャプチャ
it('processOrder returns current behavior', () => {
  const result = processOrder({ items: [], user: null });
  // 今、それが返すものが期待される値
  expect(result).toEqual({ status: 'empty', total: 0 });
});

目的: 仕様ではなく、安全ネットです。コードが何をすべきかではなく、コードが何をしているかをテストします。


フェーズ3:リファクタリング

鉄の掟: 一度に1つのリファクタリング。すべての変更後にテストを実行します。

リファクタリングカタログ

ティア1 - 常に安全(振る舞いの変更はありえない):

コードの臭い リファクタリング
不明瞭な名前 リネーム ddiscountAmount
長い関数 関数の抽出 10行を calculateTax() に抽出
不要な変数 変数のインライン化 temp = x; return temp; を削除
不適切なコード配置 関数の移動 validate()Validator クラスに移動
// ❌ 変更前: 不明瞭な名前
const d = price * 0.2;

// ✅ 変更後: リネーム
const discountAmount = price * 0.2;

ティア2 - テストがあれば安全(テストが存在すればリスクは低い):

コードの臭い リファクタリング
繰り返される式 変数の抽出 order.items.length > 0const hasItems = ...
複雑な条件式 条件式の分解 if の分岐を名前付き関数に抽出
ネストされた条件式 ガード節 深いネストの代わりに早期リターン
マジックリテラル マジックリテラルの置き換え 0.2VIP_DISCOUNT_RATE
未使用のコード デッドコードの削除 到達不能な分岐を削除
// ❌ 変更前: ネストされた条件式
function getDiscount(user) {
  if (user) {
    if (user.isVIP) {
      return 0.2;
    } else {
      return 0.1;
    }
  }
  return 0;
}

// ✅ 変更後: ガード節
function getDiscount(user) {
  if (!user) return 0;
  if (user.isVIP) return 0.2;
  return 0.1;
}

ティア3 - 注意が必要(リスクが高い、より小さなステップに分割):

コードの臭い リファクタリング 注意
ゴッドクラス クラスの抽出 段階的に、一度に1つのメソッドを移動
型チェックの条件式 ポリモーフィズムへの置き換え クラス階層が必要
パラメータが多すぎる パラメータオブジェクトの導入 関数のシグネチャを変更
複雑なループ ループをパイプラインに置き換え 同等の振る舞いを保証

タイブレーカー: 複数のリファクタリングが適用できる場合は、最初に最も小さいスコープを選択します(リネーム < 変数の抽出 < 関数の抽出 < クラスの抽出)。


フェーズ4:検証

各リファクタリング後:

  1. テストを実行 - 合格する必要がある
  2. テストに合格した場合: refactor: [変更内容] でコミット
  3. テストに失敗した場合: 直ちにリバート

リバートプロトコル

git checkout -- <変更されたファイル>

リバート後:

  • リファクタリングが大きすぎたか? → より小さなステップを試す
  • 誤って振る舞いを変更してしまったか? → アプローチを再検討する
  • 失敗したリファクタリングを「修正」しようとしないでください

2回失敗した後

停止。 ユーザーに尋ねてください:

「このリファクタリングを2回試みましたが、テストが失敗し続けています。これは、次のいずれかを示唆しています。

  1. リファクタリングが大きすぎる(より小さなステップが必要)
  2. コードに隠れた依存関係がある
  3. テストが壊れやすい

どのように進めますか?」


フェーズ5:反復

さらにリファクタリングが必要ですか?
├─ はい → フェーズ3に戻る(もう1つのリファクタリング)
└─ いいえ → 完了
    └─ レポート:「リファクタリングが完了しました。変更点:[概要]」

エッジケース

(原文がここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Refactoring

Improve code structure without changing behavior. One small step at a time.

Iron Law: ONE REFACTORING → TEST → COMMIT. Never batch changes.

When to Use

Answer IN ORDER. Stop at first match:

  1. User says "refactor", "clean up", "restructure"? → Use this skill
  2. User asks to "extract", "rename", "simplify"? → Use this skill
  3. Code smell identified? → Use this skill
  4. User wants to add feature or fix bug? → Skip (use tdd-enforcer)
  5. User wants formatting/style fixes? → Skip (use /lint)

Code smells (common triggers):

  • Duplicated code (same logic in multiple places)
  • Long function (>30 lines, doing too much)
  • Magic numbers/strings (unexplained literals)
  • Deep nesting (>3 levels of indentation)
  • Dead code (unused functions, unreachable branches)
  • Poor naming (unclear what something does)

Phase 1: ASSESS

Is this actually refactoring?

User Intent Action
"Make this cleaner" ✓ Refactoring
"Add validation" ✗ New behavior → tdd-enforcer
"Fix this bug" ✗ Bug fix → tdd-enforcer or systematic-debugger
"Format this code" ✗ Style → /lint

If not refactoring: Explain and suggest correct approach.


Phase 2: PROTECT

Does the code have tests?

Coverage Action
Well-tested Skip to Phase 3
Partial coverage Add characterization tests for untested parts
No tests Add characterization tests first

Characterization Tests

Capture current behavior before refactoring:

// Characterization test - captures ACTUAL behavior
it('processOrder returns current behavior', () => {
  const result = processOrder({ items: [], user: null });
  // Whatever it returns NOW is the expected value
  expect(result).toEqual({ status: 'empty', total: 0 });
});

Purpose: Safety net, not specification. Test what the code DOES, not what it SHOULD do.


Phase 3: REFACTOR

Iron Law: ONE refactoring at a time. Run tests after EVERY change.

Refactoring Catalog

Tier 1 - Always Safe (no behavior change possible):

Smell Refactoring Example
Unclear name Rename ddiscountAmount
Long function Extract Function Pull 10 lines into calculateTax()
Unnecessary variable Inline Variable Remove temp = x; return temp;
Misplaced code Move Function Move validate() to Validator class
// ❌ Before: unclear name
const d = price * 0.2;

// ✅ After: Rename
const discountAmount = price * 0.2;

Tier 2 - Safe with Tests (low risk if tests exist):

Smell Refactoring Example
Repeated expression Extract Variable order.items.length > 0const hasItems = ...
Complex conditional Decompose Conditional Extract if branches to named functions
Nested conditionals Guard Clauses Early returns instead of deep nesting
Magic literal Replace Magic Literal 0.2VIP_DISCOUNT_RATE
Unused code Remove Dead Code Delete unreachable branches
// ❌ Before: nested conditionals
function getDiscount(user) {
  if (user) {
    if (user.isVIP) {
      return 0.2;
    } else {
      return 0.1;
    }
  }
  return 0;
}

// ✅ After: Guard Clauses
function getDiscount(user) {
  if (!user) return 0;
  if (user.isVIP) return 0.2;
  return 0.1;
}

Tier 3 - Requires Care (higher risk, break into smaller steps):

Smell Refactoring Caution
God class Extract Class Do incrementally, move one method at a time
Type-checking conditionals Replace with Polymorphism Requires class hierarchy
Too many parameters Introduce Parameter Object Changes function signature
Complex loop Replace Loop with Pipeline Ensure equivalent behavior

Tie-breaker: If multiple refactorings apply, choose smallest scope first (Rename < Extract Variable < Extract Function < Extract Class).


Phase 4: VERIFY

After each refactoring:

  1. Run tests - Must pass
  2. If tests pass: Commit with refactor: [what changed]
  3. If tests fail: Revert immediately

Revert Protocol

git checkout -- <changed-files>

After revert:

  • Was the refactoring too large? → Try smaller step
  • Did it accidentally change behavior? → Reconsider approach
  • DO NOT attempt to "fix" a failed refactoring

After 2 Failed Attempts

STOP. Ask user:

"I've attempted this refactoring twice and tests keep failing. This suggests either:

  1. The refactoring is too large (need smaller steps)
  2. The code has hidden dependencies
  3. Tests are brittle

How would you like to proceed?"


Phase 5: ITERATE

More refactoring needed?
├─ Yes → Return to Phase 3 (one more refactoring)
└─ No → Done
    └─ Report: "Refactoring complete. Changes: [summary]"

Edge Cases

Partial test coverage:

  • Identify which functions are tested vs untested
  • Add characterization tests only for code you're about to refactor
  • Don't boil the ocean - test what you touch

Refactoring reveals a bug:

  • STOP refactoring
  • Note the bug location
  • Ask user: "Found potential bug at X. Fix it now (switching to tdd-enforcer) or continue refactoring?"

User requests large refactoring:

  • Break into steps: "I'll refactor this incrementally. First: [step 1]"
  • Complete each step fully before next
  • Never batch multiple refactorings in one edit

Anti-Patterns

Don't Do
Batch multiple refactorings One refactoring → test → commit
"Fix" a failed refactoring Revert, then try smaller step
Refactor without tests Add characterization tests first
Change behavior during refactor That's a feature/fix, not refactoring
Skip the commit Commit after every green test

Key Takeaways

  1. One change at a time - Never batch refactorings
  2. Tests before refactoring - No safety net = no refactoring
  3. Revert on failure - Don't fix, revert and retry smaller
  4. Commit after each success - refactor: [description]
  5. Smallest scope first - Rename < Extract < Move < Restructure