refactor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Refactor Skill

重构技能

Overview

概述

Language Agnostic: Examples use Python; port to your project's language.
Core Principles:
  • Functionality preserved through tests
  • Small, incremental iterations
  • All checks must pass before completion
语言无关:示例使用Python;可移植到你的项目所使用的语言。
核心原则:
  • 通过测试保留功能完整性
  • 小步、增量式迭代
  • 所有检查通过后再完成操作

Prerequisites

前置条件

Before starting refactoring:
  1. Tests must exist: If no tests exist for the code, request them first
  2. Tests must pass: Verify
    uv run pytest
    passes before starting
  3. Understand the code: Read and understand what the code does
  4. Create a backup: Optionally commit current state before changes
开始重构前:
  1. 必须已有测试:如果代码没有对应的测试,请先请求生成测试
  2. 测试必须通过:开始前先验证
    uv run pytest
    可以通过
  3. 理解代码逻辑:阅读并理解代码的功能
  4. 创建备份:可选择在修改前提交当前代码状态

Refactoring Process

重构流程

Phase 1: Analysis

阶段1:分析

  1. Read the target code thoroughly to understand its purpose
  2. Identify code smells - see code-smells.md for detection patterns
  3. List refactoring opportunities (wait for user approval before implementing)
  1. 仔细阅读目标代码,理解其用途
  2. 识别代码坏味道 - 查看code-smells.md了解检测模式
  3. 列出重构优化点(在实施前需等待用户确认)

Phase 2: TDD Cycle for Each Change

阶段2:每次改动遵循TDD循环

For each discrete refactoring iteration:
针对每一次独立的重构迭代

🔴 RED (if applicable)

🔴 红阶段(如适用)

  • If adding new simplified behavior, write a failing test first
  • If only simplifying existing code, skip to GREEN phase
  • Run tests to confirm the new test fails
  • 如果要添加新的简化行为,先编写一个失败的测试
  • 如果仅简化现有代码,直接跳转到绿阶段
  • 运行测试确认新测试失败

🟢 GREEN

🟢 绿阶段

  • Make minimal changes to pass the tests
  • Focus on making tests pass, not perfection
  • Run
    uv run pytest
    after each small change
  • Iterate until tests are green
  • 做出最小改动以通过测试
  • 专注于让测试通过,而非追求完美
  • 每次小改动后运行
    uv run pytest
  • 迭代直到测试全部通过(变绿)

🔵 REFACTOR

🔵 重构阶段

  • Apply simplification while keeping tests green
  • Extract functions, improve naming, reduce complexity
  • Continuously run tests after each small change
  • Never batch multiple changes - one small step at a time
  • 在保持测试通过的前提下进行简化操作
  • 提取函数、优化命名、降低复杂度
  • 每次小改动后持续运行测试
  • 切勿批量进行多项改动——每次只做一个小步骤

✅ VERIFY

✅ 验证阶段

  • Run
    uv run pytest
    to ensure all tests pass
  • Run
    uv run ruff check src/
    for lint checks
  • Run
    uv run mypy src/
    for type checks
  • If any check fails, fix and repeat verification
  • 运行
    uv run pytest
    确保所有测试通过
  • 运行
    uv run ruff check src/
    进行代码规范检查
  • 运行
    uv run mypy src/
    进行类型检查
  • 如果任何检查失败,修复后重复验证步骤

Phase 3: Final Verification

阶段3:最终验证

After all refactoring iterations complete:
bash
undefined
所有重构迭代完成后:
bash
undefined

Run full CI pipeline until everything passes

运行完整的CI流水线,直到所有检查通过

bin/ci-local

This runs:
1. Lint checks (`ruff`)
2. Static type checks (`mypy`)
3. Tests with coverage (`pytest`)

**Repeat** until all checks pass with no errors.
bin/ci-local

该命令会执行:
1. 代码规范检查(`ruff`)
2. 静态类型检查(`mypy`)
3. 带覆盖率统计的测试(`pytest`)

**重复执行**直到所有检查无错误通过。

Refactoring Patterns

重构模式

For common refactoring patterns with before/after examples, see patterns.md.
Includes: Prompt refactoring patterns for code that contains prompts or prompt templates.
如需查看包含前后对比示例的常见重构模式,请参阅patterns.md
**包含:**针对包含提示词或提示词模板的代码的提示词重构模式。

Examples

示例

Inline: Extract Function

内联代码:提取函数

Before - complex function with embedded calculation:
python
def generate_report(users, threshold):
    result = []
    for user in users:
        score = user.login_count * 0.3 + user.posts * 0.7
        if score >= threshold:
            result.append({"name": user.name, "score": score})
    return result
After - extracted calculation improves readability and testability:
python
def calculate_engagement_score(user) -> float:
    return user.login_count * 0.3 + user.posts * 0.7

def generate_report(users, threshold):
    result = []
    for user in users:
        score = calculate_engagement_score(user)
        if score >= threshold:
            result.append({"name": user.name, "score": score})
    return result
Single Iteration Pattern:
  1. 🔴 Write test for simplified behavior (if adding new behavior)
  2. 🟢 Make minimal changes to pass tests
  3. 🔵 Simplify while tests stay green
  4. ✅ Run
    bin/ci-local
    to verify all checks pass
Repeat for each discrete improvement.
重构前 - 包含嵌入式计算的复杂函数:
python
def generate_report(users, threshold):
    result = []
    for user in users:
        score = user.login_count * 0.3 + user.posts * 0.7
        if score >= threshold:
            result.append({"name": user.name, "score": score})
    return result
重构后 - 提取计算逻辑提升可读性和可测试性:
python
def calculate_engagement_score(user) -> float:
    return user.login_count * 0.3 + user.posts * 0.7

def generate_report(users, threshold):
    result = []
    for user in users:
        score = calculate_engagement_score(user)
        if score >= threshold:
            result.append({"name": user.name, "score": score})
    return result
单次迭代模式:
  1. 🔴 为简化后的行为编写测试(如果添加新行为)
  2. 🟢 做出最小改动以通过测试
  3. 🔵 在保持测试通过的前提下进行简化
  4. ✅ 运行
    bin/ci-local
    验证所有检查通过
针对每一个独立的优化点重复上述步骤。