systematic-refactoring

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Systematic Refactoring Skill

系统性重构技能

Purpose

目标

Perform safe, verifiable refactoring through explicit phases. Each phase has gates that prevent common refactoring mistakes: breaking behavior, incomplete migrations, or orphaned code.
通过明确的阶段执行安全、可验证的重构。每个阶段都设有管控关卡,可避免常见的重构错误:破坏原有功能、迁移不完整或产生孤立代码。

Operator Context

操作环境

This skill operates as an operator for safe code refactoring, configuring Claude's behavior for incremental, verifiable changes.
本技能作为安全代码重构的操作规范,配置Claude的行为以实现增量式、可验证的变更。

Hardcoded Behaviors (Always Apply)

硬编码行为(始终生效)

  • CLAUDE.md Compliance: Read and follow repository CLAUDE.md files before execution
  • Over-Engineering Prevention: Only refactor what's directly requested. Keep changes minimal and focused. No speculative improvements or "while we're here" changes without explicit request.
  • NEVER change behavior without tests: Characterization tests required before changes
  • NEVER make multiple changes at once: One atomic change per commit
  • NEVER skip validation: Tests must pass after every change
  • ALWAYS preserve external API: Unless explicitly requested
  • 遵循CLAUDE.md规范:执行前阅读并遵循仓库中的CLAUDE.md文件
  • 避免过度设计:仅重构直接要求的内容。保持变更最小化、聚焦化。未经明确请求,不得进行投机性改进或「顺带」修改
  • 无测试则不修改行为:变更前必须完成行为表征测试
  • 禁止同时进行多项变更:每次提交仅包含一项原子变更
  • 禁止跳过验证:每次变更后必须通过测试
  • 始终保留外部API:除非明确要求,否则不得修改外部API

Default Behaviors (ON unless disabled)

默认行为(默认开启,可关闭)

  • Communication Style: Report facts without self-congratulation. Show command output rather than describing it. Be concise but informative.
  • Temporary File Cleanup: Remove temporary test files, debug outputs, or backup files created during refactoring at task completion. Keep only files explicitly needed.
  • Write characterization tests first: Capture current behavior before changing
  • Incremental commits: Commit at each stable point
  • Update all callers: Find and update every reference
  • Remove dead code: Clean up orphaned code after migration
  • 沟通风格:仅报告事实,不自我夸赞。展示命令输出而非描述输出。简洁但信息完整
  • 临时文件清理:重构任务完成后,删除过程中创建的临时测试文件、调试输出或备份文件。仅保留明确需要的文件
  • 优先编写行为表征测试:变更前先捕获当前行为
  • 增量提交:在每个稳定点提交代码
  • 更新所有调用方:查找并更新所有引用
  • 清理无用代码:迁移后清理孤立代码

Optional Behaviors (OFF unless enabled)

可选行为(默认关闭,可开启)

  • Performance benchmarks: Compare before/after performance
  • Documentation updates: Auto-update docs for API changes
  • Type migration: Update type definitions across codebase
  • 性能基准测试:对比重构前后的性能
  • 文档自动更新:针对API变更自动更新文档
  • 类型迁移:更新整个代码库中的类型定义

What This Skill CAN Do

本技能可完成的操作

  • Safely rename functions, variables, files across a codebase
  • Extract code into new modules with caller migration
  • Change function signatures with incremental migration
  • Restructure directory layouts preserving all behavior
  • Consolidate duplicate code with test verification
  • 安全地在代码库中重命名函数、变量、文件
  • 将代码提取到新模块并完成调用方迁移
  • 增量式修改函数签名
  • 重构目录结构并保留所有原有行为
  • 通过测试验证合并重复代码

What This Skill CANNOT Do

本技能不可完成的操作

  • Fix bugs (use systematic-debugging instead)
  • Add new features (use workflow-orchestrator instead)
  • Make multiple changes simultaneously without testing between each
  • Skip characterization tests before modifying code
  • Leave incomplete migrations (old code alongside new)
  • 修复Bug(请使用systematic-debugging技能)
  • 添加新功能(请使用workflow-orchestrator技能)
  • 未在各阶段间进行测试就同时进行多项变更
  • 未编写行为表征测试就修改代码
  • 遗留未完成的迁移(旧代码与新代码并存)

Systematic Phases

系统性阶段

Phase 1: CHARACTERIZE (Do NOT proceed without test coverage)

阶段1:CHARACTERIZE(行为表征)(未完成测试覆盖则不得进入下一阶段)

Gate: Tests exist that verify current behavior.
═══════════════════════════════════════════════════════════════
 PHASE 1: CHARACTERIZE
═══════════════════════════════════════════════════════════════

 Target Code:
   - File: [path/to/file.ext]
   - Element: [function/class/module being refactored]
   - Lines: [start-end]

 Current Behavior:
   - Purpose: [what it does]
   - Inputs: [parameters/dependencies]
   - Outputs: [return values/side effects]
   - Callers: [N files/functions use this]

 Existing Tests:
   - Coverage: [X% of target code]
   - Test files: [list of relevant test files]

 Characterization Tests Written:
   - [ ] Happy path covered
   - [ ] Edge cases covered
   - [ ] Error cases covered
   - [ ] Integration points covered

 Test Execution:
   $ [test command]
   Result: ALL PASS (required to proceed)

 CHARACTERIZE complete. Proceeding to PLAN...
═══════════════════════════════════════════════════════════════
Actions in this phase:
  1. Read the code to be refactored completely
  2. Find all callers with Grep
  3. Run existing tests, note coverage gaps
  4. Write characterization tests for uncovered behavior
  5. Verify all tests pass
关卡:存在可验证当前行为的测试。
═══════════════════════════════════════════════════════════════
 阶段1:CHARACTERIZE
═══════════════════════════════════════════════════════════════

 目标代码:
   - 文件:[path/to/file.ext]
   - 元素:[待重构的函数/类/模块]
   - 行数:[起始-结束]

 当前行为:
   - 用途:[功能描述]
   - 输入:[参数/依赖]
   - 输出:[返回值/副作用]
   - 调用方:[N个文件/函数使用此元素]

 现有测试:
   - 覆盖率:[目标代码的X%]
   - 测试文件:[相关测试文件列表]

 已编写的行为表征测试:
   - [ ] 覆盖正常流程
   - [ ] 覆盖边缘情况
   - [ ] 覆盖错误场景
   - [ ] 覆盖集成点

 测试执行:
   $ [测试命令]
   结果:全部通过(必须通过才能进入下一阶段)

 CHARACTERIZE完成。进入PLAN阶段...
═══════════════════════════════════════════════════════════════
本阶段操作
  1. 完整阅读待重构的代码
  2. 使用Grep查找所有调用方
  3. 运行现有测试,记录覆盖缺口
  4. 为未覆盖的行为编写表征测试
  5. 验证所有测试通过

Phase 2: PLAN (Do NOT proceed without incremental steps defined)

阶段2:PLAN(规划)(未定义增量步骤则不得进入下一阶段)

Gate: Clear sequence of atomic changes with rollback points.
═══════════════════════════════════════════════════════════════
 PHASE 2: PLAN
═══════════════════════════════════════════════════════════════

 Refactoring Type: [rename | extract | restructure | migrate]

 Target State:
   - [Description of end state]

 Incremental Steps:
   1. [First atomic change]
      - Files affected: [list]
      - Risk: LOW/MEDIUM/HIGH
      - Rollback: [how to undo]

   2. [Second atomic change]
      - Files affected: [list]
      - Risk: LOW/MEDIUM/HIGH
      - Rollback: [how to undo]

   ... [continue for all steps]

 Dependencies:
   Step 2 depends on: Step 1
   Step 3 depends on: Step 2
   ...

 Risks:
   - [Potential issue 1]: [mitigation]
   - [Potential issue 2]: [mitigation]

 PLAN complete. Proceeding to EXECUTE...
═══════════════════════════════════════════════════════════════
Actions in this phase:
  1. Define the exact end state
  2. Break into smallest possible atomic changes
  3. Identify dependencies between steps
  4. Define rollback procedure for each step
  5. Estimate risk level for each step
关卡:明确的原子变更序列及回滚点。
═══════════════════════════════════════════════════════════════
 阶段2:PLAN
═══════════════════════════════════════════════════════════════

 重构类型:[重命名 | 提取 | 重构结构 | 迁移]

 目标状态:
   - [最终状态描述]

 增量步骤:
   1. [第一项原子变更]
      - 影响文件:[列表]
      - 风险:低/中/高
      - 回滚方式:[如何撤销]

   2. [第二项原子变更]
      - 影响文件:[列表]
      - 风险:低/中/高
      - 回滚方式:[如何撤销]

   ... [所有步骤]

 依赖关系:
   步骤2依赖于:步骤1
   步骤3依赖于:步骤2
   ...

 风险:
   - [潜在问题1]:[缓解方案]
   - [潜在问题2]:[缓解方案]

 PLAN完成。进入EXECUTE阶段...
═══════════════════════════════════════════════════════════════
本阶段操作
  1. 明确定义最终状态
  2. 拆解为最小的原子变更
  3. 标识步骤间的依赖关系
  4. 为每个步骤定义回滚流程
  5. 评估每个步骤的风险等级

Phase 3: EXECUTE (One step at a time, tests between each)

阶段3:EXECUTE(执行)(每次仅执行一项变更,变更后必须测试)

Gate: Tests pass after each atomic change.
═══════════════════════════════════════════════════════════════
 PHASE 3: EXECUTE - Step [N] of [Total]
═══════════════════════════════════════════════════════════════

 Step [N]: [description]

 Changes Made:
   - [file1.ext]: [specific change]
   - [file2.ext]: [specific change]

 Test Execution:
   $ [test command]
   Result: PASS / FAIL

 If PASS:
   Step [N] complete
   Commit: [commit message if applicable]
   Proceeding to Step [N+1]...

 If FAIL:
   Step [N] failed
   Rolling back...
   Investigating failure before retry

═══════════════════════════════════════════════════════════════
Actions in this phase:
  1. Make ONE atomic change
  2. Run ALL tests
  3. If pass: commit, move to next step
  4. If fail: rollback, investigate, fix, retry
  5. Repeat until all steps complete
关卡:每次原子变更后测试必须通过。
═══════════════════════════════════════════════════════════════
 阶段3:EXECUTE - 第[N]/[总步骤]步
═══════════════════════════════════════════════════════════════

 步骤[N]:[描述]

 已完成的变更:
   - [file1.ext]:[具体变更]
   - [file2.ext]:[具体变更]

 测试执行:
   $ [测试命令]
   结果:通过 / 失败

 如果通过:
   步骤[N]完成
   提交:[提交信息(如适用)]
   进入步骤[N+1]...

 如果失败:
   步骤[N]失败
   正在回滚...
   调查失败原因后重试

═══════════════════════════════════════════════════════════════
本阶段操作
  1. 执行一项原子变更
  2. 运行所有测试
  3. 如果通过:提交,进入下一步
  4. 如果失败:回滚,调查问题,修复后重试或修订计划
  5. 重复直到所有步骤完成

Phase 4: VALIDATE (Do NOT mark complete until verified)

阶段4:VALIDATE(验证)(未完成验证则不得标记为完成)

Gate: All original tests pass, no dead code, all callers updated.
═══════════════════════════════════════════════════════════════
 PHASE 4: VALIDATE
═══════════════════════════════════════════════════════════════

 Full Test Suite:
   $ [comprehensive test command]
   Result: [PASS/FAIL]

 Behavior Verification:
   - [ ] Original functionality preserved
   - [ ] No new failures introduced
   - [ ] Performance acceptable

 Cleanup Verification:
   - [ ] No orphaned code
   - [ ] No unused imports
   - [ ] No dead references
   - [ ] Old names completely removed

 Caller Verification:
   $ grep -r "[old_name]" --include="*.ext"
   Result: [No matches / N remaining references]

 Documentation:
   - [ ] Comments updated
   - [ ] README updated (if applicable)
   - [ ] API docs updated (if applicable)

 Final Status: COMPLETE / INCOMPLETE

 Summary:
   - Files changed: [N]
   - Lines changed: [+X/-Y]
   - Steps completed: [N/Total]
   - Tests: [X passed, Y total]

═══════════════════════════════════════════════════════════════
关卡:所有原有测试通过,无无用代码,所有调用方已更新。
═══════════════════════════════════════════════════════════════
 阶段4:VALIDATE
═══════════════════════════════════════════════════════════════

 完整测试套件:
   $ [全面测试命令]
   结果:[通过/失败]

 行为验证:
   - [ ] 原有功能保留
   - [ ] 未引入新的失败
   - [ ] 性能符合预期

 清理验证:
   - [ ] 无孤立代码
   - [ ] 无无用导入
   - [ ] 无无效引用
   - [ ] 旧名称已完全移除

 调用方验证:
   $ grep -r "[旧名称]" --include="*.ext"
   结果:[无匹配项 / 剩余N处引用]

 文档:
   - [ ] 注释已更新
   - [ ] README已更新(如适用)
   - [ ] API文档已更新(如适用)

 最终状态:完成 / 未完成

 摘要:
   - 修改文件数:[N]
   - 修改行数:[+X/-Y]
   - 完成步骤数:[N/总步骤]
   - 测试情况:[通过X项,总计Y项]

═══════════════════════════════════════════════════════════════

Refactoring Patterns

重构模式

Pattern 1: Rename (Function, Variable, File)

模式1:重命名(函数、变量、文件)

Phase 1: Find all usages with Grep
Phase 2: Plan order (definition first, then callers)
Phase 3: Execute with replace_all where safe
Phase 4: Verify no old name references remain
阶段1:使用Grep查找所有引用
阶段2:规划顺序(先修改定义,再修改调用方)
阶段3:安全情况下使用批量替换执行
阶段4:验证无旧名称引用残留

Pattern 2: Extract (Function, Module, Class)

模式2:提取(函数、模块、类)

Phase 1: Identify code to extract, write tests
Phase 2: Plan new location, interface design
Phase 3:
  - Step 1: Create new location with copy
  - Step 2: Update callers one by one
  - Step 3: Remove old code
Phase 4: Verify all callers use new location
阶段1:识别待提取的代码,编写测试
阶段2:规划新位置及接口设计
阶段3:
  - 步骤1:复制代码到新位置
  - 步骤2:逐个更新调用方
  - 步骤3:移除旧代码
阶段4:验证所有调用方均使用新位置

Pattern 3: Inline (Remove Abstraction)

模式3:内联(移除抽象)

Phase 1: Find all usages, understand all variations
Phase 2: Plan inline order (start with simplest callers)
Phase 3:
  - Step 1: Inline at first call site
  - Step 2: Repeat for each call site
  - Step 3: Remove now-unused function
Phase 4: Verify no remaining references
阶段1:查找所有引用,理解所有变体
阶段2:规划内联顺序(从最简单的调用方开始)
阶段3:
  - 步骤1:在第一个调用点内联
  - 步骤2:重复所有调用点
  - 步骤3:移除无用的函数
阶段4:验证无残留引用

Pattern 4: Change Signature

模式4:修改签名

Phase 1: Find all callers, understand usage patterns
Phase 2: Plan migration (add new, migrate, remove old)
Phase 3:
  - Step 1: Add new signature alongside old
  - Step 2: Migrate callers one by one
  - Step 3: Remove old signature
Phase 4: Verify all callers use new signature
阶段1:查找所有调用方,理解使用模式
阶段2:规划迁移步骤(先添加新签名,再迁移调用方,最后移除旧签名)
阶段3:
  - 步骤1:添加新签名
  - 步骤2:逐个迁移调用方
  - 步骤3:移除旧签名
阶段4:验证所有调用方均使用新签名

Error Handling

错误处理

Test Failure During Execute:
  • Stop immediately
  • Rollback current step
  • Investigate root cause
  • Fix and retry OR revise plan
Incomplete Caller Migration:
  • Do not remove old code until ALL callers migrated
  • Use Grep to verify zero remaining references
  • Check for dynamic references (strings, reflection)
Unexpected Dependencies:
  • Stop and return to PLAN phase
  • Add new dependencies to plan
  • May need to add intermediate steps
执行阶段测试失败
  • 立即停止
  • 回滚当前步骤
  • 调查根本原因
  • 修复后重试或修订计划
调用方迁移不完整
  • 移除旧代码前必须完成所有调用方的迁移
  • 使用Grep验证无旧名称引用残留
  • 检查动态引用(字符串、反射)
意外依赖
  • 停止并返回PLAN阶段
  • 在计划中添加新的依赖项
  • 可能需要添加中间步骤

Common Anti-Patterns

常见反模式

Anti-Pattern 1: Big Bang Refactoring

反模式1:大爆炸式重构

What it looks like:
User: "Rename getUserData to fetchUserProfile across the entire codebase"
Claude: *Changes 47 files in one commit, updating function name, all callers, tests, and docs*
Why it's wrong:
  • One test failure breaks everything
  • Impossible to bisect which change caused issues
  • No rollback points if problems discovered later
  • Merge conflicts guaranteed in active codebases
Do this instead:
  1. CHARACTERIZE: Write tests for current getUserData behavior
  2. PLAN: Break into steps (add new function, migrate callers gradually, remove old)
  3. EXECUTE: Commit after each atomic change (5-10 callers at a time)
  4. VALIDATE: Tests pass after every step
表现形式
用户:"将整个代码库中的getUserData重命名为fetchUserProfile"
Claude:*一次性修改47个文件,更新函数名、所有调用方、测试及文档*
错误原因
  • 一处测试失败会导致全部变更失效
  • 无法定位是哪项变更引发了问题
  • 后续发现问题时无回滚点
  • 活跃代码库中必然会引发合并冲突
正确做法
  1. CHARACTERIZE:使用Grep查找所有引用
  2. PLAN:规划顺序(先修改定义,再修改调用方)
  3. EXECUTE:安全情况下使用批量替换
  4. VALIDATE:验证无旧名称引用残留

Anti-Pattern 2: Refactoring Without Tests First

反模式2:无测试先重构

What it looks like:
User: "Extract this logic into a new function"
Claude: *Immediately creates new function and updates callers without writing tests*
Why it's wrong:
  • No verification that behavior is preserved
  • Silent bugs introduced during extraction
  • Can't prove refactoring was safe
  • No baseline to compare against
Do this instead:
  1. CHARACTERIZE: Write tests for current behavior BEFORE touching code
  2. Run tests: Verify they pass with current implementation
  3. Make change: Extract function
  4. Run tests again: Verify same results
  5. Tests are your proof of correctness
表现形式
用户:"将这段逻辑提取为新函数"
Claude:*直接创建新函数并更新调用方,未编写测试*
错误原因
  • 无法验证行为是否保留
  • 提取过程中可能引入隐性Bug
  • 无法证明重构是安全的
  • 无基准可对比
正确做法
  1. CHARACTERIZE:修改前先为当前行为编写测试
  2. 运行测试:验证当前实现可通过测试
  3. 进行变更:提取函数
  4. 再次运行测试:验证结果一致
  5. 测试是正确性的证明

Anti-Pattern 3: Incomplete Migration

反模式3:迁移不完整

What it looks like:
User: "Move getUser from utils.js to user-service.js"
Claude: *Creates new location, updates 80% of callers, leaves old function "for backward compatibility"*
Why it's wrong:
  • Code exists in two places indefinitely
  • Future changes need double updates
  • Confusion about which to use
  • Old code becomes stale and buggy
Do this instead:
  1. PLAN: Identify ALL callers upfront (use Grep exhaustively)
  2. EXECUTE: Update every single caller before removing old code
  3. VALIDATE: Grep confirms ZERO references to old location
  4. Clean up: Remove old code completely
  5. No half-migrated state allowed
表现形式
用户:"将getUser从utils.js移到user-service.js"
Claude:*创建新位置,更新80%的调用方,保留旧函数以实现向后兼容*
错误原因
  • 代码长期存在于两个位置
  • 后续变更需要重复修改两处
  • 开发者会混淆应使用哪个版本
  • 旧代码会逐渐过时并出现Bug
正确做法
  1. PLAN:提前识别所有调用方(使用Grep全面查找)
  2. EXECUTE:更新所有调用方后再移除旧代码
  3. VALIDATE:Grep确认无旧位置引用残留
  4. 清理:彻底移除旧代码

Anti-Pattern 4: Mixing Refactoring with Feature Work

反模式4:重构与功能开发混合

What it looks like:
User: "Rename calculateTotal and also fix the tax calculation bug"
Claude: *Renames function AND changes logic in same refactoring*
Why it's wrong:
  • Can't tell if tests fail due to rename or logic change
  • Violates "preserve behavior" principle
  • Impossible to review as pure refactoring
  • Rollback becomes unclear
Do this instead:
  1. Separate concerns: "This is ONLY refactoring, behavior unchanged"
  2. Complete refactoring first: Rename with tests proving no behavior change
  3. Then fix bug: In separate phase with new tests for fixed behavior
  4. Two commits: One refactor (safe), one fix (behavior change)
表现形式
用户:"重命名calculateTotal并修复税计算Bug"
Claude:*在同一重构中同时重命名函数并修改逻辑*
错误原因
  • 无法判断测试失败是源于重命名还是逻辑变更
  • 违反「保留行为」原则
  • 无法作为纯重构进行评审
  • 回滚操作变得模糊
正确做法
  1. 分离关注点:「本次仅为重构,不修改行为」
  2. 先完成重构:通过测试证明无行为变更
  3. 再修复Bug:在独立阶段为修复后的行为编写新测试
  4. 两次提交:一次为重构(安全),一次为Bug修复(行为变更)

References

参考资料

This skill uses these shared patterns:
  • Anti-Rationalization - Prevents shortcut rationalizations
  • Verification Checklist - Pre-completion checks
  • Gate Enforcement - Phase transition rules
本技能使用以下共享模式:
  • 反合理化 - 防止寻找捷径的合理化借口
  • 验证清单 - 完成前的检查项
  • 关卡强制执行 - 阶段转换规则

Domain-Specific Anti-Rationalization

领域特定反合理化借口

RationalizationWhy It's WrongRequired Action
"This refactoring is safe, no tests needed"Refactoring without tests is flying blindWrite characterization tests first
"I'll update the remaining callers later"Incomplete migrations rot foreverMigrate ALL callers before removing old code
"Small rename, no need for full process"Small renames break string refs and configsGrep for all references including strings
"I can fix this bug while refactoring"Mixed concerns make failures undiagnosableSeparate commits: refactor then fix
合理化借口错误原因要求操作
"这次重构很安全,不需要测试"无测试的重构相当于盲目操作先编写行为表征测试
"剩余的调用方后续再更新"未完成的迁移会长期存在完成所有调用方迁移后再移除旧代码
"小重命名不需要完整流程"小重命名可能破坏字符串引用或配置使用Grep查找所有引用,包括字符串
"重构时顺便修复Bug"混合关注点会导致测试失败原因不明分离提交:一次为重构(安全),一次为Bug修复