Refactor Code Safely with TDD
TDD refactor skill using a tdd-orchestrator agent to apply design patterns and SOLID principles while keeping all tests green.
Why it matters
Enhance code quality and maintainability by refactoring existing codebases. This asset ensures all tests remain green throughout the refactoring process, applying best practices and design patterns.
Outcomes
What it gets done
Establish a green baseline by running existing tests.
Detect and address code smells using established techniques.
Apply relevant design patterns and SOLID principles.
Optimize code performance and verify improvements.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/ag-tdd-workflows-tdd-refactor | bash Overview
Tdd Workflows Tdd Refactor
A TDD refactor skill using a dedicated tdd-orchestrator agent to apply code-smell fixes, design patterns, and SOLID principles incrementally while keeping all tests green. Use for refactoring existing tested code; not for introducing new behavior, which stays separate from the refactoring process.
What it does
This skill refactors code with confidence using a comprehensive test safety net, invoked via the Task tool with subagent_type="tdd-orchestrator" (an Opus-model agent) to perform sophisticated refactoring while keeping all tests green. The core process runs ten steps: pre-assessment (run tests for a green baseline, analyze code smells and coverage, document current performance), code smell detection (duplicated code to extracted methods, long methods decomposed, large classes split by responsibility, primitive obsession to value objects, switch statements to polymorphism), applying design patterns (Creational, Structural, Behavioral, Domain - only where they add clear value) and SOLID principles.
When to use - and when NOT to
Use it for refactoring existing code under test coverage - not for introducing new behavior, which the process explicitly keeps separate from refactoring. A worked example shows the pattern in action, extracting validation and orchestration out of a monolithic method:
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();
}
}
applying Extract Method, Value Objects, Dependency Injection, and async patterns together.
Inputs and outputs
Refactoring techniques cover Extract Method/Variable/Interface, inlining unnecessary indirection, renaming for clarity, moving methods/fields, replacing magic numbers with constants, and replacing conditionals with polymorphism. Performance optimization profiles first, then optimizes algorithms/data structures, adds caching, eliminates N+1 queries, and always measures before and after. Changes are applied incrementally - small atomic edits, tests run after each one, a commit after each successful step - with architecture-evolution techniques (Strangler Fig, Branch by Abstraction, Parallel Change, Mikado Method) reserved for large-scale changes. Output includes the refactored code, all-green test results, before/after metrics, the list of applied techniques, and a remaining technical-debt assessment.
Integrations
A safety checklist gates every commit: 100% tests passing, no functionality regression, acceptable performance metrics, maintained or improved code coverage, and updated documentation. If tests fail mid-refactor, the recovery protocol is to immediately revert the last change, identify what broke it, and apply smaller increments rather than pushing forward.
Who it's for
Developers refactoring existing code who want a systematic, test-safety-netted process - code smell detection through design patterns, SOLID, and incremental verified changes - delegated to a dedicated orchestrator agent rather than freehand restructuring.
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.