Use when working with tdd workflows tdd refactor
Add this skill
npx mdskills install sickn33/tdd-workflows-tdd-refactorComprehensive TDD refactoring guide with detailed patterns, code smells, and SOLID principles
1---2name: tdd-workflows-tdd-refactor3description: "Use when working with tdd workflows tdd refactor"4---56## Use this skill when78- Working on tdd workflows tdd refactor tasks or workflows9- Needing guidance, best practices, or checklists for tdd workflows tdd refactor1011## Do not use this skill when1213- The task is unrelated to tdd workflows tdd refactor14- You need a different domain or tool outside this scope1516## Instructions1718- Clarify goals, constraints, and required inputs.19- Apply relevant best practices and validate outcomes.20- Provide actionable steps and verification.21- If detailed examples are required, open `resources/implementation-playbook.md`.2223Refactor code with confidence using comprehensive test safety net:2425[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.]2627## Usage2829Use Task tool with subagent_type="tdd-orchestrator" to perform safe refactoring.3031Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD refactor phase:3233## Core Process3435**1. Pre-Assessment**36- Run tests to establish green baseline37- Analyze code smells and test coverage38- Document current performance metrics39- Create incremental refactoring plan4041**2. Code Smell Detection**42- Duplicated code → Extract methods/classes43- Long methods → Decompose into focused functions44- Large classes → Split responsibilities45- Long parameter lists → Parameter objects46- Feature Envy → Move methods to appropriate classes47- Primitive Obsession → Value objects48- Switch statements → Polymorphism49- Dead code → Remove5051**3. Design Patterns**52- Apply Creational (Factory, Builder, Singleton)53- Apply Structural (Adapter, Facade, Decorator)54- Apply Behavioral (Strategy, Observer, Command)55- Apply Domain (Repository, Service, Value Objects)56- Use patterns only where they add clear value5758**4. SOLID Principles**59- Single Responsibility: One reason to change60- Open/Closed: Open for extension, closed for modification61- Liskov Substitution: Subtypes substitutable62- Interface Segregation: Small, focused interfaces63- Dependency Inversion: Depend on abstractions6465**5. Refactoring Techniques**66- Extract Method/Variable/Interface67- Inline unnecessary indirection68- Rename for clarity69- Move Method/Field to appropriate classes70- Replace Magic Numbers with constants71- Encapsulate fields72- Replace Conditional with Polymorphism73- Introduce Null Object7475**6. Performance Optimization**76- Profile to identify bottlenecks77- Optimize algorithms and data structures78- Implement caching where beneficial79- Reduce database queries (N+1 elimination)80- Lazy loading and pagination81- Always measure before and after8283**7. Incremental Steps**84- Make small, atomic changes85- Run tests after each modification86- Commit after each successful refactoring87- Keep refactoring separate from behavior changes88- Use scaffolding when needed8990**8. Architecture Evolution**91- Layer separation and dependency management92- Module boundaries and interface definition93- Event-driven patterns for decoupling94- Database access pattern optimization9596**9. Safety Verification**97- Run full test suite after each change98- Performance regression testing99- Mutation testing for test effectiveness100- Rollback plan for major changes101102**10. Advanced Patterns**103- Strangler Fig: Gradual legacy replacement104- Branch by Abstraction: Large-scale changes105- Parallel Change: Expand-contract pattern106- Mikado Method: Dependency graph navigation107108## Output Requirements109110- Refactored code with improvements applied111- Test results (all green)112- Before/after metrics comparison113- Applied refactoring techniques list114- Performance improvement measurements115- Remaining technical debt assessment116117## Safety Checklist118119Before committing:120- ✓ All tests pass (100% green)121- ✓ No functionality regression122- ✓ Performance metrics acceptable123- ✓ Code coverage maintained/improved124- ✓ Documentation updated125126## Recovery Protocol127128If tests fail:129- Immediately revert last change130- Identify breaking refactoring131- Apply smaller incremental changes132- Use version control for safe experimentation133134## Example: Extract Method Pattern135136**Before:**137```typescript138class OrderProcessor {139 processOrder(order: Order): ProcessResult {140 // Validation141 if (!order.customerId || order.items.length === 0) {142 return { success: false, error: "Invalid order" };143 }144145 // Calculate totals146 let subtotal = 0;147 for (const item of order.items) {148 subtotal += item.price * item.quantity;149 }150 let total = subtotal + (subtotal * 0.08) + (subtotal > 100 ? 0 : 15);151152 // Process payment...153 // Update inventory...154 // Send confirmation...155 }156}157```158159**After:**160```typescript161class OrderProcessor {162 async processOrder(order: Order): Promise<ProcessResult> {163 const validation = this.validateOrder(order);164 if (!validation.isValid) return ProcessResult.failure(validation.error);165166 const orderTotal = OrderTotal.calculate(order);167 const inventoryCheck = await this.inventoryService.checkAvailability(order.items);168 if (!inventoryCheck.available) return ProcessResult.failure(inventoryCheck.reason);169170 await this.paymentService.processPayment(order.paymentMethod, orderTotal.total);171 await this.inventoryService.reserveItems(order.items);172 await this.notificationService.sendOrderConfirmation(order, orderTotal);173174 return ProcessResult.success(order.id, orderTotal.total);175 }176177 private validateOrder(order: Order): ValidationResult {178 if (!order.customerId) return ValidationResult.invalid("Customer ID required");179 if (order.items.length === 0) return ValidationResult.invalid("Order must contain items");180 return ValidationResult.valid();181 }182}183```184185**Applied:** Extract Method, Value Objects, Dependency Injection, Async patterns186187Code to refactor: $ARGUMENTS"188
Full transparency — inspect the skill content before installing.