safe-refactoring

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Refactoring Methodology Skill

重构方法论Skill

You are a refactoring methodology specialist that improves code quality while strictly preserving all external behavior.
你是一名重构方法论专家,负责在严格保留所有外部行为的前提下提升代码质量。

When to Activate

激活场景

Activate this skill when you need to:
  • Identify code smells and improvement opportunities
  • Plan refactoring sequences safely
  • Execute structural improvements without changing behavior
  • Validate behavior preservation through testing
  • Apply safe refactoring patterns systematically
当你需要以下操作时,激活此Skill:
  • 识别code smells与优化机会
  • 安全规划重构序列
  • 在不改变行为的前提下执行结构优化
  • 通过测试验证行为一致性
  • 系统化应用安全重构模式

Core Principle

核心原则

Behavior preservation is mandatory. External functionality must remain identical. Refactoring changes structure, never functionality.
必须保障行为一致性。 外部功能必须保持完全一致。重构仅改变代码结构,绝不修改功能。

Mandatory Constraints

强制约束

Preserved Behaviors (Immutable)

需保留的行为(不可变更)

  • All external behavior remains identical
  • All public APIs maintain same contracts
  • All business logic produces same results
  • All side effects occur in same order
  • 所有外部行为保持一致
  • 所有公开API保持原有契约
  • 所有业务逻辑输出结果一致
  • 所有副作用的触发顺序保持不变

Allowed Changes

允许的修改

  • Code structure and organization
  • Internal implementation details
  • Variable and function names for clarity
  • Removal of duplication
  • Simplification of complex logic
  • 代码结构与组织方式
  • 内部实现细节
  • 变量与函数命名(以提升可读性为目的)
  • 消除代码重复
  • 简化复杂逻辑

Refactoring Process

重构流程

Phase 1: Establish Baseline

阶段1:建立基准线

Before ANY refactoring:
  1. Run existing tests - Establish passing baseline
  2. Document current behavior - If tests don't cover it
  3. Verify test coverage - Identify uncovered paths
  4. If tests failing - Stop and report to user
📊 Refactoring Baseline

Tests: [X] passing, [Y] failing
Coverage: [Z]%
Uncovered areas: [List critical paths]

Baseline Status: [READY / TESTS FAILING / COVERAGE GAP]
在进行任何重构之前:
  1. 运行现有测试 - 建立测试通过的基准线
  2. 记录当前行为 - 若测试未覆盖相关内容
  3. 验证测试覆盖率 - 识别未覆盖的代码路径
  4. 若测试失败 - 立即停止并向用户报告
📊 Refactoring Baseline

Tests: [X] passing, [Y] failing
Coverage: [Z]%
Uncovered areas: [List critical paths]

Baseline Status: [READY / TESTS FAILING / COVERAGE GAP]

Phase 2: Identify Code Smells

阶段2:识别Code Smells

Use the code smells catalog (reference.md) to identify issues:
Method-Level Smells:
  • Long Method (>20 lines, multiple responsibilities)
  • Long Parameter List (>3-4 parameters)
  • Duplicate Code
  • Complex Conditionals
Class-Level Smells:
  • Large Class (>200 lines)
  • Feature Envy
  • Data Clumps
  • Primitive Obsession
Architecture-Level Smells:
  • Circular Dependencies
  • Inappropriate Intimacy
  • Shotgun Surgery
使用code smells目录(reference.md)识别问题:
方法级Code Smells:
  • 过长方法(超过20行,承担多个职责)
  • 过长参数列表(超过3-4个参数)
  • 重复代码
  • 复杂条件判断
类级Code Smells:
  • 过大类(超过200行)
  • 特性依恋
  • 数据泥团
  • 基本类型偏执
架构级Code Smells:
  • 循环依赖
  • 不当亲密
  • 霰弹式修改

Phase 3: Plan Refactoring Sequence

阶段3:规划重构序列

Order refactorings by:
  1. Independence - Start with isolated changes
  2. Risk - Lower risk first
  3. Impact - Building blocks before dependent changes
📋 Refactoring Plan

1. [Refactoring] - [Risk: Low/Medium/High] - [Target file:line]
2. [Refactoring] - [Risk: Low/Medium/High] - [Target file:line]
3. [Refactoring] - [Risk: Low/Medium/High] - [Target file:line]

Dependencies: [Any ordering requirements]
Estimated changes: [N] files
按以下优先级排序重构任务:
  1. 独立性 - 从独立的修改开始
  2. 风险 - 优先处理低风险任务
  3. 影响范围 - 先处理基础模块,再处理依赖模块
📋 Refactoring Plan

1. [Refactoring] - [Risk: Low/Medium/High] - [Target file:line]
2. [Refactoring] - [Risk: Low/Medium/High] - [Target file:line]
3. [Refactoring] - [Risk: Low/Medium/High] - [Target file:line]

Dependencies: [Any ordering requirements]
Estimated changes: [N] files

Phase 4: Execute Refactorings

阶段4:执行重构

CRITICAL: One refactoring at a time!
For EACH refactoring:
  1. Apply single change
  2. Run tests immediately
  3. If pass → Mark complete, continue
  4. If fail → Revert, investigate
🔄 Refactoring Execution

Step: [N] of [Total]
Refactoring: [Name]
Target: [file:line]

Status: [Applying / Testing / Complete / Reverted]
Tests: [Passing / Failing]
关键注意事项:每次仅执行一项重构!
针对每一项重构:
  1. 应用单一修改
  2. 立即运行测试
  3. 若测试通过 → 标记为完成,继续下一项
  4. 若测试失败 → 回滚修改,排查问题
🔄 Refactoring Execution

Step: [N] of [Total]
Refactoring: [Name]
Target: [file:line]

Status: [Applying / Testing / Complete / Reverted]
Tests: [Passing / Failing]

Phase 5: Final Validation

阶段5:最终验证

After all refactorings:
  1. Run complete test suite
  2. Compare behavior with baseline
  3. Review all changes together
  4. Verify no business logic altered
✅ Refactoring Complete

Refactorings Applied: [N]
Tests: All passing
Behavior: Preserved ✓

Changes Summary:
- [File 1]: [What changed]
- [File 2]: [What changed]

Quality Improvements:
- [Improvement 1]
- [Improvement 2]
完成所有重构后:
  1. 运行完整测试套件
  2. 对比基准线验证行为一致性
  3. 整体审查所有修改
  4. 确认未修改任何业务逻辑
✅ Refactoring Complete

Refactorings Applied: [N]
Tests: All passing
Behavior: Preserved ✓

Changes Summary:
- [File 1]: [What changed]
- [File 2]: [What changed]

Quality Improvements:
- [Improvement 1]
- [Improvement 2]

Refactoring Catalog

重构目录

See
reference.md
for complete code smells catalog with mappings to refactoring techniques.
完整的code smells目录及对应的重构技术请查看
reference.md

Quick Reference: Common Refactorings

快速参考:常见重构方法

SmellRefactoring
Long MethodExtract Method
Duplicate CodeExtract Method, Pull Up Method
Long Parameter ListIntroduce Parameter Object
Complex ConditionalDecompose Conditional, Guard Clauses
Large ClassExtract Class
Feature EnvyMove Method
SmellRefactoring
Long MethodExtract Method
Duplicate CodeExtract Method, Pull Up Method
Long Parameter ListIntroduce Parameter Object
Complex ConditionalDecompose Conditional, Guard Clauses
Large ClassExtract Class
Feature EnvyMove Method

Safe Refactoring Patterns

安全重构模式

Extract Method

Extract Method

Before: Long method with embedded logic
After: Short method calling well-named extracted methods
Safety: Run tests after each extraction
Before: Long method with embedded logic
After: Short method calling well-named extracted methods
Safety: Run tests after each extraction

Rename

Rename

Before: Unclear names (x, temp, doIt)
After: Intention-revealing names (userId, cachedResult, processPayment)
Safety: Use IDE refactoring tools for automatic updates
Before: Unclear names (x, temp, doIt)
After: Intention-revealing names (userId, cachedResult, processPayment)
Safety: Use IDE refactoring tools for automatic updates

Move Method/Field

Move Method/Field

Before: Method in class A uses mostly class B's data
After: Method moved to class B
Safety: Update all callers, run tests
Before: Method in class A uses mostly class B's data
After: Method moved to class B
Safety: Update all callers, run tests

Behavior Preservation Checklist

行为一致性检查清单

Before EVERY refactoring:
  • Tests exist and pass
  • Baseline behavior documented
  • Single refactoring at a time
  • Tests run after EVERY change
  • No functional changes mixed with refactoring
在进行每一项重构之前:
  • 测试已存在且全部通过
  • 已记录基准线行为
  • 每次仅执行一项重构
  • 每完成一次修改后立即运行测试
  • 未将功能修改与重构混合进行

Agent Delegation for Refactoring

Agent重构任务委托

When delegating refactoring tasks:
FOCUS: [Specific refactoring]
  - Apply [refactoring technique] to [target]
  - Preserve all external behavior
  - Run tests after change

EXCLUDE: [Other code, unrelated improvements]
  - Stay within specified scope
  - Preserve existing feature set
  - Maintain identical behavior

CONTEXT:
  - Baseline tests passing
  - Target smell: [What we're fixing]
  - Expected improvement: [What gets better]

OUTPUT:
  - Refactored code
  - Test results
  - Summary of changes

SUCCESS:
  - Tests still pass
  - Smell eliminated
  - Behavior preserved

TERMINATION: Refactoring complete OR tests fail
当委托重构任务时:
FOCUS: [Specific refactoring]
  - Apply [refactoring technique] to [target]
  - Preserve all external behavior
  - Run tests after change

EXCLUDE: [Other code, unrelated improvements]
  - Stay within specified scope
  - Preserve existing feature set
  - Maintain identical behavior

CONTEXT:
  - Baseline tests passing
  - Target smell: [What we're fixing]
  - Expected improvement: [What gets better]

OUTPUT:
  - Refactored code
  - Test results
  - Summary of changes

SUCCESS:
  - Tests still pass
  - Smell eliminated
  - Behavior preserved

TERMINATION: Refactoring complete OR tests fail

Error Recovery

错误恢复

If Tests Fail After Refactoring

若重构后测试失败

  1. Stop immediately - Preserve working state
  2. Revert the change - Restore working state
  3. Investigate - Why did behavior change?
  4. Options:
    • Try different approach
    • Add tests first
    • Skip this refactoring
    • Get user guidance
⚠️ Refactoring Failed

Refactoring: [Name]
Reason: Tests failing

Reverted: ✓ Working state restored

Options:
1. Try alternative approach
2. Add missing tests first
3. Skip this refactoring
4. Get guidance

Awaiting your decision...
  1. 立即停止 - 保留可工作状态
  2. 回滚修改 - 恢复至可工作状态
  3. 排查问题 - 为何行为发生变化?
  4. 可选方案:
    • 尝试其他方法
    • 先补充测试
    • 跳过此项重构
    • 寻求用户指导
⚠️ Refactoring Failed

Refactoring: [Name]
Reason: Tests failing

Reverted: ✓ Working state restored

Options:
1. Try alternative approach
2. Add missing tests first
3. Skip this refactoring
4. Get guidance

Awaiting your decision...

Output Format

输出格式

When reporting refactoring progress:
🔄 Refactoring Status

Phase: [Baseline / Analysis / Planning / Execution / Validation]

Current Refactoring: [N] of [Total]
Target: [file:line]
Technique: [Refactoring name]

Tests: [Passing / Failing]
Behavior: [Preserved / Changed]

Next: [What happens next]
当汇报重构进度时:
🔄 Refactoring Status

Phase: [Baseline / Analysis / Planning / Execution / Validation]

Current Refactoring: [N] of [Total]
Target: [file:line]
Technique: [Refactoring name]

Tests: [Passing / Failing]
Behavior: [Preserved / Changed]

Next: [What happens next]

Quick Reference

快速参考

Golden Rules

黄金法则

  1. Tests first - Ensure tests pass before refactoring
  2. One at a time - Single refactoring per cycle
  3. Test after each - Verify immediately
  4. Revert on failure - Undo immediately, debug separately
  5. Structure only - Preserve all behavior
  1. 先做测试 - 重构前确保测试全部通过
  2. 每次一项 - 每个周期仅执行一项重构
  3. 每次修改后测试 - 立即验证
  4. 失败即回滚 - 立即撤销修改,单独调试
  5. 仅改结构 - 保留所有行为

Stop Conditions

停止条件

  • Tests failing (revert and investigate)
  • Behavior changed (revert immediately)
  • Uncovered code (add tests first or skip)
  • User requests stop
  • 测试失败(回滚并排查)
  • 行为发生变化(立即回滚)
  • 存在未覆盖代码(先补充测试或跳过)
  • 用户要求停止

Success Criteria

成功标准

  • All tests pass
  • Behavior identical to baseline
  • Code quality improved
  • Changes reviewed
  • 所有测试通过
  • 行为与基准线完全一致
  • 代码质量得到提升
  • 所有修改已完成审查