tdd-workflows-tdd-refactor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUse this skill when
以下场景适用本技能
- Working on tdd workflows tdd refactor tasks or workflows
- Needing guidance, best practices, or checklists for tdd workflows tdd refactor
- 处理TDD工作流、TDD重构任务或相关工作流程时
- 需要TDD工作流、TDD重构的指导、最佳实践或检查清单时
Do not use this skill when
以下场景不适用本技能
- The task is unrelated to tdd workflows tdd refactor
- You need a different domain or tool outside this scope
- 任务与TDD工作流、TDD重构无关时
- 需要该范围之外的其他领域或工具时
Instructions
操作说明
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open .
resources/implementation-playbook.md
Refactor code with confidence using comprehensive test safety net:
[Extended thinking: This tool uses the tdd-orchestrator agent (opus model) for sophisticated refactoring while maintaining all tests green. It applies design patterns, improves code quality, and optimizes performance with the safety of comprehensive test coverage.]
- 明确目标、约束条件和所需输入。
- 应用相关最佳实践并验证结果。
- 提供可执行的步骤与验证方式。
- 如果需要详细示例,请打开。
resources/implementation-playbook.md
借助全面的测试安全网,自信地重构代码:
[扩展说明:本工具使用tdd-orchestrator Agent(opus模型)进行复杂重构,同时保持所有测试通过。它应用设计模式、提升代码质量,并在全面测试覆盖的保障下优化性能。]
Usage
使用方法
Use Task tool with subagent_type="tdd-orchestrator" to perform safe refactoring.
Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD refactor phase:
使用Task工具,设置subagent_type="tdd-orchestrator"以执行安全重构。
提示语:"Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD refactor phase:
Core Process
核心流程
1. Pre-Assessment
- Run tests to establish green baseline
- Analyze code smells and test coverage
- Document current performance metrics
- Create incremental refactoring plan
2. Code Smell Detection
- Duplicated code → Extract methods/classes
- Long methods → Decompose into focused functions
- Large classes → Split responsibilities
- Long parameter lists → Parameter objects
- Feature Envy → Move methods to appropriate classes
- Primitive Obsession → Value objects
- Switch statements → Polymorphism
- Dead code → Remove
3. Design Patterns
- Apply Creational (Factory, Builder, Singleton)
- Apply Structural (Adapter, Facade, Decorator)
- Apply Behavioral (Strategy, Observer, Command)
- Apply Domain (Repository, Service, Value Objects)
- Use patterns only where they add clear value
4. SOLID Principles
- Single Responsibility: One reason to change
- Open/Closed: Open for extension, closed for modification
- Liskov Substitution: Subtypes substitutable
- Interface Segregation: Small, focused interfaces
- Dependency Inversion: Depend on abstractions
5. Refactoring Techniques
- Extract Method/Variable/Interface
- Inline unnecessary indirection
- Rename for clarity
- Move Method/Field to appropriate classes
- Replace Magic Numbers with constants
- Encapsulate fields
- Replace Conditional with Polymorphism
- Introduce Null Object
6. Performance Optimization
- Profile to identify bottlenecks
- Optimize algorithms and data structures
- Implement caching where beneficial
- Reduce database queries (N+1 elimination)
- Lazy loading and pagination
- Always measure before and after
7. Incremental Steps
- Make small, atomic changes
- Run tests after each modification
- Commit after each successful refactoring
- Keep refactoring separate from behavior changes
- Use scaffolding when needed
8. Architecture Evolution
- Layer separation and dependency management
- Module boundaries and interface definition
- Event-driven patterns for decoupling
- Database access pattern optimization
9. Safety Verification
- Run full test suite after each change
- Performance regression testing
- Mutation testing for test effectiveness
- Rollback plan for major changes
10. Advanced Patterns
- Strangler Fig: Gradual legacy replacement
- Branch by Abstraction: Large-scale changes
- Parallel Change: Expand-contract pattern
- Mikado Method: Dependency graph navigation
1. 预评估
- 运行测试以建立通过基准
- 分析代码异味与测试覆盖率
- 记录当前性能指标
- 创建增量重构计划
2. 代码异味检测
- 重复代码 → 提取方法/类
- 过长方法 → 分解为专注的函数
- 过大类 → 拆分职责
- 过长参数列表 → 使用参数对象
- 特性依恋 → 将方法移至合适的类
- 基本类型偏执 → 使用值对象
- 分支语句 → 替换为多态
- 死代码 → 删除
3. 设计模式
- 应用创建型模式(Factory、Builder、Singleton)
- 应用结构型模式(Adapter、Facade、Decorator)
- 应用行为型模式(Strategy、Observer、Command)
- 应用领域模式(Repository、Service、Value Objects)
- 仅在能带来明确价值的场景下使用模式
4. SOLID原则
- 单一职责原则:一个类只应有一个引起它变化的原因
- 开闭原则:对扩展开放,对修改关闭
- 里氏替换原则:子类可替换父类使用
- 接口隔离原则:使用小而专注的接口
- 依赖倒置原则:依赖抽象而非具体实现
5. 重构技巧
- 提取方法/变量/接口
- 内联不必要的间接层
- 重命名以提升清晰度
- 将方法/字段移至合适的类
- 用常量替换魔法值
- 封装字段
- 用多态替换条件分支
- 引入空对象
6. 性能优化
- 通过性能分析识别瓶颈
- 优化算法与数据结构
- 在合适场景实现缓存
- 减少数据库查询(消除N+1问题)
- 懒加载与分页
- 优化前后务必进行性能测量
7. 增量步骤
- 做出小而原子的变更
- 每次修改后运行测试
- 每次成功重构后提交代码
- 将重构与业务逻辑变更分开
- 必要时使用脚手架
8. 架构演进
- 分层与依赖管理
- 模块边界与接口定义
- 事件驱动模式实现解耦
- 数据库访问模式优化
9. 安全验证
- 每次变更后运行完整测试套件
- 性能回归测试
- 变异测试验证测试有效性
- 重大变更的回滚计划
10. 高级模式
- 绞杀者模式:逐步替换遗留系统
- 抽象分支:大规模变更
- 并行变更:扩展-收缩模式
- 米卡多方法:依赖图导航
Output Requirements
输出要求
- Refactored code with improvements applied
- Test results (all green)
- Before/after metrics comparison
- Applied refactoring techniques list
- Performance improvement measurements
- Remaining technical debt assessment
- 应用改进后的重构代码
- 测试结果(全部通过)
- 优化前后指标对比
- 已应用的重构技术列表
- 性能提升测量数据
- 剩余技术债务评估
Safety Checklist
安全检查清单
Before committing:
- ✓ All tests pass (100% green)
- ✓ No functionality regression
- ✓ Performance metrics acceptable
- ✓ Code coverage maintained/improved
- ✓ Documentation updated
提交前确认:
- ✓ 所有测试通过(100%通过)
- ✓ 无功能回归
- ✓ 性能指标符合要求
- ✓ 测试覆盖率保持或提升
- ✓ 文档已更新
Recovery Protocol
恢复协议
If tests fail:
- Immediately revert last change
- Identify breaking refactoring
- Apply smaller incremental changes
- Use version control for safe experimentation
如果测试失败:
- 立即回滚上一次变更
- 定位导致失败的重构操作
- 应用更小的增量变更
- 使用版本控制进行安全实验
Example: Extract Method Pattern
示例:提取方法模式
Before:
typescript
class OrderProcessor {
processOrder(order: Order): ProcessResult {
// Validation
if (!order.customerId || order.items.length === 0) {
return { success: false, error: "Invalid order" };
}
// Calculate totals
let subtotal = 0;
for (const item of order.items) {
subtotal += item.price * item.quantity;
}
let total = subtotal + (subtotal * 0.08) + (subtotal > 100 ? 0 : 15);
// Process payment...
// Update inventory...
// Send confirmation...
}
}After:
typescript
class OrderProcessor {
async processOrder(order: Order): Promise<ProcessResult> {
const validation = this.validateOrder(order);
if (!validation.isValid) return ProcessResult.failure(validation.error);
const orderTotal = OrderTotal.calculate(order);
const inventoryCheck = await this.inventoryService.checkAvailability(order.items);
if (!inventoryCheck.available) return ProcessResult.failure(inventoryCheck.reason);
await this.paymentService.processPayment(order.paymentMethod, orderTotal.total);
await this.inventoryService.reserveItems(order.items);
await this.notificationService.sendOrderConfirmation(order, orderTotal);
return ProcessResult.success(order.id, orderTotal.total);
}
private validateOrder(order: Order): ValidationResult {
if (!order.customerId) return ValidationResult.invalid("Customer ID required");
if (order.items.length === 0) return ValidationResult.invalid("Order must contain items");
return ValidationResult.valid();
}
}Applied: Extract Method, Value Objects, Dependency Injection, Async patterns
Code to refactor: $ARGUMENTS"
重构前:
typescript
class OrderProcessor {
processOrder(order: Order): ProcessResult {
// Validation
if (!order.customerId || order.items.length === 0) {
return { success: false, error: "Invalid order" };
}
// Calculate totals
let subtotal = 0;
for (const item of order.items) {
subtotal += item.price * item.quantity;
}
let total = subtotal + (subtotal * 0.08) + (subtotal > 100 ? 0 : 15);
// Process payment...
// Update inventory...
// Send confirmation...
}
}重构后:
typescript
class OrderProcessor {
async processOrder(order: Order): Promise<ProcessResult> {
const validation = this.validateOrder(order);
if (!validation.isValid) return ProcessResult.failure(validation.error);
const orderTotal = OrderTotal.calculate(order);
const inventoryCheck = await this.inventoryService.checkAvailability(order.items);
if (!inventoryCheck.available) return ProcessResult.failure(inventoryCheck.reason);
await this.paymentService.processPayment(order.paymentMethod, orderTotal.total);
await this.inventoryService.reserveItems(order.items);
await this.notificationService.sendOrderConfirmation(order, orderTotal);
return ProcessResult.success(order.id, orderTotal.total);
}
private validateOrder(order: Order): ValidationResult {
if (!order.customerId) return ValidationResult.invalid("Customer ID required");
if (order.items.length === 0) return ValidationResult.invalid("Order must contain items");
return ValidationResult.valid();
}
}应用的技术: 提取方法、值对象、依赖注入、异步模式
待重构代码:$ARGUMENTS"