Use this skill when
Working on tdd workflows tdd refactor tasks or workflowsNeeding guidance, best practices, or checklists for tdd workflows tdd refactorDo not use this skill when
The task is unrelated to tdd workflows tdd refactorYou need a different domain or tool outside this scopeInstructions
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.]
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:
Core Process
1. Pre-Assessment
Run tests to establish green baselineAnalyze code smells and test coverageDocument current performance metricsCreate incremental refactoring plan2. Code Smell Detection
Duplicated code → Extract methods/classesLong methods → Decompose into focused functionsLarge classes → Split responsibilitiesLong parameter lists → Parameter objectsFeature Envy → Move methods to appropriate classesPrimitive Obsession → Value objectsSwitch statements → PolymorphismDead code → Remove3. 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 value4. SOLID Principles
Single Responsibility: One reason to changeOpen/Closed: Open for extension, closed for modificationLiskov Substitution: Subtypes substitutableInterface Segregation: Small, focused interfacesDependency Inversion: Depend on abstractions5. Refactoring Techniques
Extract Method/Variable/InterfaceInline unnecessary indirectionRename for clarityMove Method/Field to appropriate classesReplace Magic Numbers with constantsEncapsulate fieldsReplace Conditional with PolymorphismIntroduce Null Object6. Performance Optimization
Profile to identify bottlenecksOptimize algorithms and data structuresImplement caching where beneficialReduce database queries (N+1 elimination)Lazy loading and paginationAlways measure before and after7. Incremental Steps
Make small, atomic changesRun tests after each modificationCommit after each successful refactoringKeep refactoring separate from behavior changesUse scaffolding when needed8. Architecture Evolution
Layer separation and dependency managementModule boundaries and interface definitionEvent-driven patterns for decouplingDatabase access pattern optimization9. Safety Verification
Run full test suite after each changePerformance regression testingMutation testing for test effectivenessRollback plan for major changes10. Advanced Patterns
Strangler Fig: Gradual legacy replacementBranch by Abstraction: Large-scale changesParallel Change: Expand-contract patternMikado Method: Dependency graph navigationOutput Requirements
Refactored code with improvements appliedTest results (all green)Before/after metrics comparisonApplied refactoring techniques listPerformance improvement measurementsRemaining technical debt assessmentSafety Checklist
Before committing:
✓ All tests pass (100% green)✓ No functionality regression✓ Performance metrics acceptable✓ Code coverage maintained/improved✓ Documentation updatedRecovery Protocol
If tests fail:
Immediately revert last changeIdentify breaking refactoringApply smaller incremental changesUse version control for safe experimentationExample: Extract Method Pattern
Before:
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:
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"