refactor-flow
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineserefactor-flow
refactor-flow
Description: Code refactoring assistance, technical debt management, and documentation synchronization
Category: Code Quality & Maintenance
Complexity: Medium-High (code transformation + traceability maintenance)
描述:代码重构辅助、技术债务管理与文档同步
分类:代码质量与维护
复杂度:中高(代码转换 + 可追溯性维护)
Purpose
目标
Improve code quality through systematic refactoring while maintaining traceability to specifications. Identify refactoring opportunities, guide safe transformations, and ensure documentation stays synchronized with code changes.
通过系统化重构提升代码质量,同时保持与规格说明的可追溯性。识别重构机会,指导安全的代码转换,并确保文档与代码变更保持同步。
Capabilities
核心能力
1. Code Smell Detection
1. 代码异味检测
- Long methods: Functions >50 lines
- God classes: Classes with too many responsibilities
- Duplicate code: Similar code blocks
- Dead code: Unused functions/variables
- Magic numbers: Hardcoded constants
- Complex conditionals: Nested if statements
- Feature envy: Methods using other class data extensively
- Data clumps: Groups of data that travel together
- 过长方法:函数超过50行
- God Class:承担过多职责的类
- 重复代码:相似代码块
- 死代码:未使用的函数/变量
- 魔法数字:硬编码常量
- 复杂条件语句:嵌套if结构
- 特性羡慕:过度依赖其他类数据的方法
- 数据泥团:总是一起出现的数据组
2. Refactoring Recommendations
2. 重构建议
- Extract method: Break down long functions
- Extract class: Split god classes
- Rename: Improve naming clarity
- Remove duplication: DRY principle
- Simplify conditionals: Guard clauses, strategy pattern
- Introduce parameter object: Replace parameter lists
- Replace magic numbers: Named constants
- Inline method: Remove unnecessary indirection
- 提取方法:拆分过长函数
- 提取类:拆分God Class
- 重命名:提升命名清晰度
- 消除重复:遵循DRY原则
- 简化条件语句:卫语句、策略模式
- 引入参数对象:替换参数列表
- 替换魔法数字:使用命名常量
- 内联方法:移除不必要的间接层
3. Complexity Reduction
3. 复杂度降低
- Reduce cyclomatic complexity
- Simplify nested structures
- Break dependency cycles
- Improve cohesion
- Reduce coupling
- 降低圈复杂度
- 简化嵌套结构
- 打破依赖循环
- 提高内聚性
- 降低耦合度
4. Design Pattern Application
4. 设计模式应用
- Identify pattern opportunities
- Suggest appropriate patterns
- Guide pattern implementation
- Validate pattern usage
- 识别模式适用场景
- 推荐合适的设计模式
- 指导模式实现
- 验证模式使用合理性
5. Technical Debt Tracking
5. 技术债务追踪
- Identify technical debt
- Quantify debt severity
- Prioritize debt reduction
- Track debt trends
- 识别技术债务
- 量化债务严重程度
- 优先处理债务
- 追踪债务趋势
6. Documentation Synchronization
6. 文档同步
- Update docstrings after refactoring
- Sync SPEC documents with code changes
- Update traceability references
- Maintain ADR compliance
- 重构后更新文档字符串
- 同步SPEC文档与代码变更
- 更新可追溯性引用
- 保持ADR合规性
7. Safe Refactoring
7. 安全重构
- Verify tests exist before refactoring
- Ensure tests pass after refactoring
- Preserve public API contracts
- Maintain backward compatibility
- 重构前验证测试是否存在
- 重构后确保测试通过
- 保留公共API契约
- 保持向后兼容性
8. Automated Refactoring
8. 自动化重构
- Auto-fix simple refactorings
- Generate refactoring diffs
- Apply transformations safely
- Rollback capability
- 自动修复简单重构项
- 生成重构差异
- 安全应用代码转换
- 支持回滚操作
Refactoring Workflow
重构工作流
mermaid
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]mermaid
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]Usage Instructions
使用说明
Analyze Code for Refactoring
分析代码以识别重构机会
bash
refactor-flow analyze --file src/auth/service.pyOutput:
=== 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 hoursbash
refactor-flow analyze --file src/auth/service.py输出:
=== Refactoring Analysis: src/auth/service.py ===
发现代码异味:6处
[高优先级] 过长方法(第45-156行)
- 方法:authenticate_user()
- 长度:112行
- 复杂度:15
- 建议:将验证逻辑提取到独立方法
- 预估工作量:2小时
- 风险:低(测试覆盖率良好:95%)
[高优先级] 重复代码(相似度85%)
- 位置:
* 第201-215行(validate_password_strength)
* 第234-248行(validate_new_password)
- 建议:将通用逻辑提取到共享验证器
- 预估工作量:1小时
- 风险:低
[中优先级] God Class
- 类:UserAuthenticationService
- 职责数量:7个(认证、验证、日志、缓存、邮件、审计、会话)
- 建议:将邮件、审计和缓存功能提取到独立服务
- 预估工作量:4小时
- 风险:中(影响多个消费者)
[中优先级] 复杂条件语句(第89-103行)
- 嵌套深度:4层
- 建议:使用卫语句和提前返回
- 预估工作量:30分钟
- 风险:低
[低优先级] 魔法数字(第167、189、203行)
- 值:3、5、10
- 建议:提取为命名常量
- 预估工作量:15分钟
- 风险:极低
[低优先级] 死代码(第278-295行)
- 方法:legacy_authentication()
- 最后使用时间:从未(6个月前添加)
- 建议:确认未使用后删除
- 预估工作量:5分钟
- 风险:极低
技术债务得分:42/100(高债务)
重构优先级:高
总预估工作量:7.75小时Generate Refactoring Plan
生成重构计划
bash
refactor-flow plan \
--file src/auth/service.py \
--priority high \
--output refactoring-plan.mdGenerated plan:
markdown
undefinedbash
refactor-flow plan \
--file src/auth/service.py \
--priority high \
--output refactoring-plan.md生成的计划:
markdown
undefinedRefactoring Plan: UserAuthenticationService
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
- 复杂度:15(高)
- 代码行数:356
- 测试覆盖率:95%
- 技术债务:42/100
Target State
目标状态
- Complexity: <10 (Acceptable)
- Lines of code: <250
- Test coverage: ≥95%
- Technical debt: <20/100
- 复杂度:<10(可接受)
- 代码行数:<250
- 测试覆盖率:≥95%
- 技术债务:<20/100
Refactoring Steps
重构步骤
Step 1: Extract Password Validation (Priority: High, Risk: Low)
步骤1:提取密码验证(优先级:高,风险:低)
Duration: 1 hour
Changes:
- Create class
PasswordValidator - Move logic
validate_password_strength() - Remove duplicate validation code
- 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 validationAfter:
python
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 logicVerification:
- Tests pass
- Coverage maintained
- No duplicate code
时长:1小时
变更:
- 创建类
PasswordValidator - 迁移逻辑
validate_password_strength() - 删除重复验证代码
- 更新测试
重构前:
python
def validate_password_strength(self, password):
if len(password) < 8:
return False
if not any(c.isupper() for c in password):
return False
# ... 更多验证逻辑重构后:
python
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")
# ... 验证逻辑验证项:
- 测试通过
- 覆盖率保持不变
- 无重复代码
Step 2: Simplify authenticate_user() (Priority: High, Risk: Low)
步骤2:简化authenticate_user()(优先级:高,风险:低)
Duration: 2 hours
Changes:
- Extract validation logic to
_validate_credentials() - Extract session creation to
_create_session() - Extract audit logging to
_audit_login_attempt() - Use guard clauses
Before (Complexity: 15):
python
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 linesAfter (Complexity: 5):
python
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)Verification:
- Complexity reduced to <10
- All tests pass
- Behavior unchanged
时长:2小时
变更:
- 将验证逻辑提取到2.将会话创建逻辑提取到
_validate_credentials()3.将审计日志逻辑提取到_create_session()_audit_login_attempt() - 使用卫语句
重构前(复杂度:15):
python
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行代码重构后(复杂度:5):
python
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
- 所有测试通过
- 行为无变更
Step 3: Extract Supporting Services (Priority: Medium, Risk: Medium)
步骤3:提取支撑服务(优先级:中,风险:中)
Duration: 4 hours
Changes:
- Create for email notifications
EmailService - Create for security audit logging
AuditLogger - Create for session caching
SessionCache - Update dependency injection
Impact Analysis:
- 5 consumers of UserAuthenticationService
- All consumers need to update imports
- Breaking change (MAJOR version bump)
- Migration guide required
Migration Guide:
python
undefined时长:4小时
变更:
- 创建处理邮件通知
EmailService - 创建处理安全审计日志
AuditLogger - 创建处理会话缓存
SessionCache - 更新依赖注入
影响分析:
- UserAuthenticationService的5个消费者
- 所有消费者需更新导入
- 破坏性变更(主版本号升级)
- 需要迁移指南
迁移指南:
python
undefinedBefore
重构前
auth_service = UserAuthenticationService()
auth_service.send_verification_email(user)
auth_service = UserAuthenticationService()
auth_service.send_verification_email(user)
After
重构后
auth_service = UserAuthenticationService()
email_service = EmailService()
email_service.send_verification(user)
**Verification**:
- [ ] All consumers updated
- [ ] Integration tests pass
- [ ] Documentation updatedauth_service = UserAuthenticationService()
email_service = EmailService()
email_service.send_verification(user)
**验证项**:
- [ ] 所有消费者已更新
- [ ] 集成测试通过
- [ ] 文档已更新Execute Refactoring
执行重构
bash
refactor-flow execute \
--plan refactoring-plan.md \
--step 1 \
--dry-runDry-run output:
=== 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)bash
refactor-flow execute \
--plan refactoring-plan.md \
--step 1 \
--dry-run试运行输出:
=== Refactoring Execution (DRY RUN) ===
步骤1:提取密码验证
待执行变更:
1. 创建新文件: src/auth/validators.py
[+] 45行
2. 修改文件: src/auth/service.py
[-] 30行(移除重复代码)
[~] 12行(更新为使用PasswordValidator)
3. 创建测试文件: tests/auth/test_validators.py
[+] 67行
差异预览:
────────────────────────────────────────
--- 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
- # ... (移除28行)
+ def validate_password_strength(self, password: str) -> bool:
+ result = PasswordValidator.validate(password)
+ return result.valid
────────────────────────────────────────
测试影响:
- 需更新测试: 3个
- 新增测试: 8个
- 总测试数: 156 → 161
是否执行?(--dry-run已启用,未做任何变更)Track Technical Debt
追踪技术债务
bash
refactor-flow debt \
--module src/ \
--output reports/technical-debt.jsonOutput:
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"
}
}bash
refactor-flow debt \
--module src/ \
--output reports/technical-debt.json输出:
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"
}
}Refactoring Patterns
重构模式
Extract Method
提取方法
Before:
python
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 totalAfter:
python
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重构前:
python
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重构后:
python
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 + shippingReplace Conditional with Polymorphism
用多态替换条件语句
Before:
python
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 0After:
python
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')重构前:
python
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重构后:
python
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')Introduce Parameter Object
引入参数对象
Before:
python
def create_user(username, email, first_name, last_name, birth_date,
address, city, state, zip_code, phone, preferences):
# ... implementationAfter:
python
@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重构前:
python
def create_user(username, email, first_name, last_name, birth_date,
address, city, state, zip_code, phone, preferences):
# ... implementation重构后:
python
@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:
# ... implementationRefactoring Checklist
重构检查清单
Pre-Refactoring
重构前
- Understand the code behavior
- Check test coverage (≥80% recommended)
- Review SPEC/ADR compliance
- Identify affected consumers
- Create backup branch
- Run full test suite (baseline)
- 理解代码行为
- 检查测试覆盖率(建议≥80%)
- 审查SPEC/ADR合规性
- 识别受影响的消费者
- 创建备份分支
- 运行完整测试套件(基准测试)
During Refactoring
重构中
- Make small, incremental changes
- Run tests after each change
- Commit frequently with clear messages
- Preserve public API contracts
- Maintain backward compatibility (if required)
- Update inline documentation
- 进行小幅度、增量式变更
- 每次变更后运行测试
- 频繁提交,提交信息清晰
- 保留公共API契约
- 保持向后兼容性(如有要求)
- 更新内联文档
Post-Refactoring
重构后
- Run full test suite
- Verify coverage maintained/improved
- Update SPEC documents if API changed
- Update traceability references
- Check ADR compliance
- Update changelog
- Code review
- Performance testing (if applicable)
- 运行完整测试套件
- 验证覆盖率保持或提升
- 若API变更,更新SPEC文档
- 更新可追溯性引用
- 检查ADR合规性
- 更新变更日志
- 代码评审
- 性能测试(如适用)
Documentation Synchronization
文档同步
After Extract Method
提取方法后
python
undefinedpython
undefinedBefore 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
"""def authenticate_user(username, password):
"""
使用用户名和密码认证用户。
验证凭证,检查用户状态,创建会话。
可追溯性: 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
"""undefineddef authenticate_user(username: str, password: str) -> AuthResult:
"""
使用用户名和密码认证用户。
参数:
username: 用户登录名
password: 用户密码
返回:
包含认证状态和会话的AuthResult
可追溯性: REQ-AUTH-01, BDD-LOGIN-001
"""def _validate_credentials(self, username: str, password: str) -> ValidationResult:
"""
验证用户名和密码格式。
可追溯性: REQ-AUTH-01
"""undefinedUpdate SPEC Document
更新SPEC文档
markdown
undefinedmarkdown
undefinedSPEC-AUTH-V1.md
SPEC-AUTH-V1.md
Authentication Service API
认证服务API
Method: authenticate_user()
方法: authenticate_user()
Status: Updated in v1.2.0 (refactored for clarity)
Signature:
python
def authenticate_user(username: str, password: str) -> AuthResultChanges in v1.2.0:
- Refactored internal implementation for better maintainability
- No API changes (backward compatible)
- Improved error messages
- Added type hints
Traceability: REQ-AUTH-01
---状态: v1.2.0中更新(为提升清晰度进行重构)
签名:
python
def authenticate_user(username: str, password: str) -> AuthResultv1.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
- 重命名变量/方法(借助IDE支持)
- 提取常量
- 内联临时变量
- 删除死代码
- 添加类型提示
- 优化文档字符串
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
- 修改类继承结构
- 拆分数据库表
- 修改公共API
- 变更认证机制
- 重构核心业务逻辑
Risk Mitigation
风险缓解措施
- Excellent test coverage: ≥95% for high-risk refactorings
- Feature flags: Enable gradual rollout
- Parallel run: Run old and new code, compare results
- Staged rollout: Canary deployment
- Rollback plan: Quick revert capability
- Monitoring: Extra logging during transition
- 优秀的测试覆盖率: 高风险重构需≥95%覆盖率
- 特性开关: 支持逐步发布
- 并行运行: 同时运行新旧代码,对比结果
- 分阶段部署: 金丝雀发布
- 回滚计划: 快速回滚能力
- 监控: 过渡阶段增加日志
Tool Access
工具权限
Required tools:
- : Read source files and documentation
Read - : Apply refactoring transformations
Edit - : Create new files
Write - : Run tests and analysis tools
Bash - : Search for code patterns
Grep
Required libraries:
- rope: Python refactoring library
- autopep8: Code formatting
- radon: Complexity metrics
- pylint: Code analysis
所需工具:
- : 读取源文件和文档
Read - : 应用重构转换
Edit - : 创建新文件
Write - : 运行测试和分析工具
Bash - : 搜索代码模式
Grep
所需库:
- rope: Python重构库
- autopep8: 代码格式化
- radon: 复杂度指标
- pylint: 代码分析
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
最佳实践
- Test first: Ensure good test coverage before refactoring
- Small steps: Incremental changes, frequent commits
- One thing at a time: Don't mix refactoring with new features
- Preserve behavior: No functional changes during refactoring
- Run tests constantly: After every small change
- Review changes: Code review for refactorings
- Update documentation: Keep specs synchronized
- Monitor performance: Ensure no performance regressions
- Communicate: Notify team of significant refactorings
- 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%
- 代码复杂度降至目标水平
- 测试覆盖率保持或提升
- 零功能回归
- 文档保持同步
- 可追溯性得以保留
- 团队理解变更内容
- 技术债务得分提升≥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
- 重构计划保存至
plans/refactoring/ - 重构报告位于
reports/refactoring/ - 技术债务追踪文件为
metrics/technical-debt.json - 自动化重构需人工评审
- 高风险重构需团队批准