mcpField
R
refactor-flow

refactor-flow

github.com/vladm3105开发1758 次安装1 天前更新
代码仓库

关于 refactor-flow

refactor-flow 面向需要重构代码、管理技术债并保持规格文档与代码一致的开发者。它涵盖代码异味分析、重构规划、安全变更和文档同步。

主要功能

  1. 01检测代码异味与复杂度
  2. 02推荐重构模式
  3. 03规划并应用代码变更
  4. 04跟踪并确定技术债优先级
  5. 05同步规格文档与追溯关系
  6. 06检查测试并维护 API 契约

适用场景

  1. 01重构前评估代码模块
  2. 02规划复杂服务的分阶段改动
  3. 03代码变更后更新规格文档
  4. 04确定各模块技术债的优先级

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill refactor-flow

安装后在 Claude Code 中输入/refactor-flow确认已加载。

详细介绍

refactor-flow

描述:代码重构辅助、技术债务管理和文档同步

类别:代码质量与维护

复杂度:中高(代码转换 + 可追溯性维护)


目的

在保持与规范可追溯性的同时,通过系统化重构提升代码质量。识别重构机会,指导安全转换,并确保文档与代码变更保持同步。


功能

1. 代码异味检测
  • 过长方法:超过 50 行的函数
  • 上帝类:职责过多的类
  • 重复代码:相似的代码块
  • 死代码:未使用的函数/变量
  • 魔法数字:硬编码的常量
  • 复杂条件判断:嵌套的 if 语句
  • 特性嫉妒:大量使用其他类数据的方法
  • 数据泥团:总是一起传递的数据组
2. 重构建议
  • 提取方法:拆分过长的函数
  • 提取类:拆分上帝类
  • 重命名:提升命名清晰度
  • 消除重复:遵循 DRY 原则
  • 简化条件判断:使用卫语句、策略模式
  • 引入参数对象:替换参数列表
  • 替换魔法数字:使用命名常量
  • 内联方法:移除不必要的间接调用
3. 降低复杂度
  • 降低圈复杂度
  • 简化嵌套结构
  • 打破依赖循环
  • 提升内聚性
  • 降低耦合度
4. 应用设计模式
  • 识别模式应用机会
  • 建议合适的模式
  • 指导模式实现
  • 验证模式用法
5. 技术债务跟踪
  • 识别技术债务
  • 量化债务严重程度
  • 确定债务削减优先级
  • 跟踪债务趋势
6. 文档同步
  • 重构后更新文档字符串
  • 将 SPEC 文档与代码变更同步
  • 更新可追溯性引用
  • 确保符合 ADR
7. 安全重构
  • 重构前确认测试存在
  • 确保重构后测试通过
  • 保留公共 API 契约
  • 保持向后兼容性
8. 自动化重构
  • 自动修复简单重构
  • 生成重构差异
  • 安全地应用转换
  • 支持回滚

重构工作流

graph TD
    A[Code Analysis] --> B[Detect Code Smells]
    B --> C{Smells Found?}
    C -->|No| D[Code Quality Good]
    C -->|Yes| E[Prioritize Issues]

    E --> F[Check Test Coverage]
    F --> G{Tests Adequate?}
    G -->|No| H[Write Tests First]
    G -->|Yes| I[Plan Refactoring]

    H --> I
    I --> J[Generate Refactoring Steps]
    J --> K[Execute Refactoring]

    K --> L[Run Tests]
    L --> M{Tests Pass?}
    M -->|No| N[Rollback Changes]
    M -->|Yes| O[Update Documentation]

    N --> P[Revise Approach]
    P --> I

    O --> Q[Validate Traceability]
    Q --> R[Check ADR Compliance]
    R --> S[Generate Refactoring Report]

    S --> T[Commit Changes]

使用说明

分析代码以进行重构
refactor-flow analyze --file src/auth/service.py

输出:

=== Refactoring Analysis: src/auth/service.py ===

Code Smells Found: 6

[HIGH] Long Method (Lines 45-156)
- Method: authenticate_user()
- Length: 112 lines
- Complexity: 15
- Recommendation: Extract validation logic to separate methods
- Estimated effort: 2 hours
- Risk: Low (good test coverage: 95%)

[HIGH] Duplicate Code (85% similarity)
- Locations:
  * Lines 201-215 (validate_password_strength)
  * Lines 234-248 (validate_new_password)
- Recommendation: Extract common logic to shared validator
- Estimated effort: 1 hour
- Risk: Low

[MEDIUM] God Class
- Class: UserAuthenticationService
- Responsibilities: 7 (authentication, validation, logging, caching, email, audit, session)
- Recommendation: Extract email, audit, and caching to separate services
- Estimated effort: 4 hours
- Risk: Medium (affects multiple consumers)

[MEDIUM] Complex Conditional (Lines 89-103)
- Nested depth: 4
- Recommendation: Use guard clauses and early returns
- Estimated effort: 30 minutes
- Risk: Low

[LOW] Magic Numbers (Lines 167, 189, 203)
- Values: 3, 5, 10
- Recommendation: Extract to named constants
- Estimated effort: 15 minutes
- Risk: Very low

[LOW] Dead Code (Lines 278-295)
- Method: legacy_authentication()
- Last used: Never (added 6 months ago)
- Recommendation: Remove if truly unused
- Estimated effort: 5 minutes
- Risk: Very low

Technical Debt Score: 42/100 (High debt)
Refactoring Priority: High
Estimated Total Effort: 7.75 hours
生成重构计划
refactor-flow plan \
  --file src/auth/service.py \
  --priority high \
  --output refactoring-plan.md

生成的计划:

# Refactoring Plan: UserAuthenticationService

## Objective
Reduce complexity and improve maintainability of authentication service

## Current State
- Complexity: 15 (High)
- Lines of code: 356
- Test coverage: 95%
- Technical debt: 42/100

## Target State
- Complexity: <10 (Acceptable)
- Lines of code: <250
- Test coverage: ≥95%
- Technical debt: <20/100

## Refactoring Steps

### Step 1: Extract Password Validation (Priority: High, Risk: Low)
**Duration**: 1 hour

**Changes**:
1. Create `PasswordValidator` class
2. Move `validate_password_strength()` logic
3. Remove duplicate validation code
4. Update tests

**Before**:
```python
def validate_password_strength(self, password):
    if len(password) < 8:
        return False
    if not any(c.isupper() for c in password):
        return False
    # ... more validation

之后:

class PasswordValidator:
    MIN_LENGTH = 8
    MAX_LENGTH = 128

    @classmethod
    def validate(cls, password: str) -> ValidationResult:
        if len(password) < cls.MIN_LENGTH:
            return ValidationResult(valid=False, error="Too short")
        # ... validation logic

验证:

  • 测试通过
  • 覆盖率保持不变
  • 没有重复代码

步骤 2:简化 authenticate_user()(优先级:高,风险:低)

时长:2 小时

变更:

  1. 将验证逻辑提取到 _validate_credentials()
  2. 将会话创建逻辑提取到 _create_session()
  3. 将审计日志记录逻辑提取到 _audit_login_attempt()
  4. 使用卫语句

之前(复杂度:15):

def authenticate_user(self, username, password):
    if username and password:
        if self._validate_format(username):
            user = self.db.get_user(username)
            if user:
                if user.is_active:
                    if self._check_password(password, user.password_hash):
                        # ... 50 more lines

之后(复杂度:5):

def authenticate_user(self, username: str, password: str) -> AuthResult:
    credentials = self._validate_credentials(username, password)
    if not credentials.valid:
        return AuthResult(success=False, error=credentials.error)

    user = self._get_active_user(username)
    if not user:
        return AuthResult(success=False, error="User not found")

    if not self._verify_password(password, user):
        self._audit_login_attempt(username, success=False)
        return AuthResult(success=False, error="Invalid password")

    session = self._create_session(user)
    self._audit_login_attempt(username, success=True)
    return AuthResult(success=True, session=session)

验证:

  • 复杂度降至 <10
  • 所有测试通过
  • 行为未改变

步骤 3:提取支持服务(优先级:中,风险:中)

时长:4 小时

变更:

  1. 创建用于电子邮件通知的 EmailService
  2. 创建用于安全审计日志记录的 AuditLogger
  3. 创建用于会话缓存的 SessionCache
  4. 更新依赖注入

影响分析:

  • 有 5 个使用者依赖 UserAuthenticationService
  • 所有使用者都需要更新导入
  • 属于破坏性变更(主版本号递增)
  • 需要迁移指南

迁移指南:

# Before
auth_service = UserAuthenticationService()
auth_service.send_verification_email(user)

# After
auth_service = UserAuthenticationService()
email_service = EmailService()
email_service.send_verification(user)

验证:

  • 所有使用者已更新
  • 集成测试通过
  • 文档已更新

### Execute Refactoring

```bash
refactor-flow execute \
  --plan refactoring-plan.md \
  --step 1 \
  --dry-run

试运行输出:

=== Refactoring Execution (DRY RUN) ===

Step 1: Extract Password Validation

Changes to be made:

1. Create new file: src/auth/validators.py
   [+] 45 lines

2. Modify file: src/auth/service.py
   [-] 30 lines (removed duplicate code)
   [~] 12 lines (updated to use PasswordValidator)

3. Create test file: tests/auth/test_validators.py
   [+] 67 lines

Diff preview:
────────────────────────────────────────
--- src/auth/service.py
+++ src/auth/service.py
@@ -1,5 +1,6 @@
 from datetime import datetime
 from typing import Optional
+from auth.validators import PasswordValidator

 class UserAuthenticationService:
-    def validate_password_strength(self, password: str) -> bool:
-        if len(password) < 8:
-            return False
-        # ... (removed 28 lines)
+    def validate_password_strength(self, password: str) -> bool:
+        result = PasswordValidator.validate(password)
+        return result.valid
────────────────────────────────────────

Test impact:
- Tests to update: 3
- New tests: 8
- Total test count: 156 → 161

Ready to execute? (--dry-run flag active, no changes made)
跟踪技术债务
refactor-flow debt \
  --module src/ \
  --output reports/technical-debt.json

输出:

{
  "summary": {
    "total_debt_score": 35,
    "critical_debt_items": 3,
    "high_debt_items": 12,
    "medium_debt_items": 28,
    "estimated_hours": 87
  },
  "debt_by_category": {
    "complexity": {
      "score": 45,
      "items": 8,
      "estimated_hours": 24
    },
    "duplication": {
      "score": 30,
      "items": 15,
      "estimated_hours": 18
    },
    "test_coverage": {
      "score": 20,
      "items": 12,
      "estimated_hours": 30
    },
    "documentation": {
      "score": 25,
      "items": 9,
      "estimated_hours": 15
    }
  },
  "critical_items": [
    {
      "file": "src/data/processor.py",
      "issue": "God class with 12 responsibilities",
      "debt_score": 85,
      "estimated_hours": 16,
      "recommendation": "Split into domain-specific services"
    },
    {
      "file": "src/api/handlers.py",
      "issue": "850 lines, complexity 45",
      "debt_score": 92,
      "estimated_hours": 20,
      "recommendation": "Extract handlers to separate modules"
    }
  ],
  "trend": {
    "previous_score": 40,
    "current_score": 35,
    "change": -5,
    "direction": "improving"
  }
}

重构模式

提取方法

之前:

def process_order(order):
    # Validate order (15 lines)
    if not order.items:
        raise ValueError("No items")
    for item in order.items:
        if item.quantity <= 0:
            raise ValueError("Invalid quantity")
    # ... more validation

    # Calculate total (10 lines)
    subtotal = sum(item.price * item.quantity for item in order.items)
    tax = subtotal * 0.08
    shipping = calculate_shipping(order)
    total = subtotal + tax + shipping

    # Process payment (20 lines)
    # ... payment logic

    return total

之后:

def process_order(order: Order) -> Decimal:
    self._validate_order(order)
    total = self._calculate_total(order)
    self._process_payment(order, total)
    return total

def _validate_order(self, order: Order) -> None:
    if not order.items:
        raise ValueError("No items")
    for item in order.items:
        if item.quantity <= 0:
            raise ValueError(f"Invalid quantity for {item.name}")

def _calculate_total(self, order: Order) -> Decimal:
    subtotal = sum(item.price * item.quantity for item in order.items)
    tax = subtotal * Decimal('0.08')
    shipping = self._calculate_shipping(order)
    return subtotal + tax + shipping
用多态替换条件判断

之前:

def calculate_discount(customer, amount):
    if customer.type == 'regular':
        return amount * 0.05
    elif customer.type == 'premium':
        return amount * 0.10
    elif customer.type == 'vip':
        return amount * 0.20
    else:
        return 0

之后:

class Customer(ABC):
    @abstractmethod
    def calculate_discount(self, amount: Decimal) -> Decimal:
        pass

class RegularCustomer(Customer):
    def calculate_discount(self, amount: Decimal) -> Decimal:
        return amount * Decimal('0.05')

class PremiumCustomer(Customer):
    def calculate_discount(self, amount: Decimal) -> Decimal:
        return amount * Decimal('0.10')

class VIPCustomer(Customer):
    def calculate_discount(self, amount: Decimal) -> Decimal:
        return amount * Decimal('0.20')
引入参数对象

之前:

def create_user(username, email, first_name, last_name, birth_date,
                address, city, state, zip_code, phone, preferences):
    # ... implementation

之后:

@dataclass
class UserProfile:
    username: str
    email: str
    first_name: str
    last_name: str
    birth_date: date
    contact_info: ContactInfo
    preferences: UserPreferences

def create_user(profile: UserProfile) -> User:
    # ... implementation

重构检查清单

重构前
  • 了解代码行为
  • 检查测试覆盖率(建议 ≥80%)
  • 审查 SPEC/ADR 合规性
  • 识别受影响的使用方
  • 创建备份分支
  • 运行完整测试套件(基线)
重构期间
  • 进行小幅、渐进式修改
  • 每次修改后运行测试
  • 使用清晰的提交说明,频繁提交
  • 保持公共 API 契约
  • 保持向后兼容(如有要求)
  • 更新内联文档
重构后
  • 运行完整测试套件
  • 确认覆盖率保持不变或有所提升
  • 如果 API 有变化,更新 SPEC 文档
  • 更新可追溯性引用
  • 检查 ADR 合规性
  • 更新变更日志
  • 代码审查
  • 性能测试(如适用)

文档同步

提取方法后
# Before refactoring
def authenticate_user(username, password):
    """
    Authenticate user with username and password.
    Validates credentials, checks user status, creates session.

    Traceability: REQ-AUTH-01, BDD-LOGIN-001
    """

# After refactoring - Update all affected docstrings
def authenticate_user(username: str, password: str) -> AuthResult:
    """
    Authenticate user with username and password.

    Args:
        username: User's login name
        password: User's password

    Returns:
        AuthResult containing success status and session

    Traceability: REQ-AUTH-01, BDD-LOGIN-001
    """

def _validate_credentials(self, username: str, password: str) -> ValidationResult:
    """
    Validate username and password format.

    Traceability: REQ-AUTH-01
    """
更新 SPEC 文档
# SPEC-AUTH-V1.md

## Authentication Service API

### Method: authenticate_user()
**Status**: Updated in v1.2.0 (refactored for clarity)

**Signature**:
```python
def authenticate_user(username: str, password: str) -> AuthResult

v1.2.0 中的变更:

  • 重构内部实现,以提升可维护性
  • 未更改 API(向后兼容)
  • 改进错误消息
  • 添加类型提示

可追溯性:REQ-AUTH-01


---

## Risk Assessment

### Low Risk Refactorings
- Rename variables/methods (with IDE support)
- Extract constants
- Inline temporary variables
- Remove dead code
- Add type hints
- Improve docstrings

### Medium Risk Refactorings
- Extract method
- Extract class
- Move method
- Replace conditional with polymorphism
- Introduce parameter object

### High Risk Refactorings
- Change class hierarchy
- Split database tables
- Modify public API
- Change authentication mechanism
- Refactor core business logic

### Risk Mitigation
1. **Excellent test coverage**: ≥95% for high-risk refactorings
2. **Feature flags**: Enable gradual rollout
3. **Parallel run**: Run old and new code, compare results
4. **Staged rollout**: Canary deployment
5. **Rollback plan**: Quick revert capability
6. **Monitoring**: Extra logging during transition

---

## Tool Access

Required tools:
- `Read`: Read source files and documentation
- `Edit`: Apply refactoring transformations
- `Write`: Create new files
- `Bash`: Run tests and analysis tools
- `Grep`: Search for code patterns

Required libraries:
- rope: Python refactoring library
- autopep8: Code formatting
- radon: Complexity metrics
- pylint: Code analysis

---

## Integration Points

### With code-review
- Identify refactoring opportunities from reviews
- Validate refactoring quality
- Track complexity improvements

### With test-automation
- Ensure tests exist before refactoring
- Run tests after each refactoring step
- Verify coverage maintained

### With doc-validator
- Sync documentation with code changes
- Validate traceability after refactoring
- Update cross-references

### With analytics-flow
- Track technical debt trends
- Measure refactoring impact
- Report debt reduction progress

---

## Best Practices

1. **Test first**: Ensure good test coverage before refactoring
2. **Small steps**: Incremental changes, frequent commits
3. **One thing at a time**: Don't mix refactoring with new features
4. **Preserve behavior**: No functional changes during refactoring
5. **Run tests constantly**: After every small change
6. **Review changes**: Code review for refactorings
7. **Update documentation**: Keep specs synchronized
8. **Monitor performance**: Ensure no performance regressions
9. **Communicate**: Notify team of significant refactorings
10. **Schedule wisely**: Not during critical deadlines

---

## Success Criteria

- Code complexity reduced to target levels
- Test coverage maintained or improved
- Zero functional regressions
- Documentation synchronized
- Traceability preserved
- Team understands changes
- Technical debt score improved by ≥20%

---

## Notes

- Refactoring plans saved to `plans/refactoring/`
- Refactoring reports in `reports/refactoring/`
- Technical debt tracked in `metrics/technical-debt.json`
- Automated refactorings require manual review
- High-risk refactorings need team approval

评论

支持 Markdown