/refactor
/refactor - Refactoring Command
Section titled “/refactor - Refactoring Command”Purpose
Section titled “Purpose”Improve code structure, readability, or performance without changing external behavior. Applies proven refactoring patterns to make code more maintainable, testable, and efficient.
/refactor [file or function] [goal: clean | extract | simplify | optimize]Arguments
Section titled “Arguments”[file or function]- Target code to refactor[goal]- Optional refactoring objective:clean- Remove dead code, improve namingextract- Extract reusable functions/componentssimplify- Reduce complexity and nestingoptimize- Improve performance
How It Works
Section titled “How It Works”The /refactor command follows a safe, incremental approach:
Step 1: Understand Current Code
Section titled “Step 1: Understand Current Code”-
Read Thoroughly
- Analyzes what the code does
- Identifies its purpose and responsibilities
- Maps inputs, outputs, and side effects
-
Note Existing Tests
- Finds test coverage for the code
- Ensures tests exist before refactoring
- If no tests exist, generates them first
-
Identify Patterns
- Recognizes code smells
- Finds refactoring opportunities
- Notes dependencies and coupling
Step 2: Plan Refactoring
Section titled “Step 2: Plan Refactoring”-
Identify Improvements
- Code smells to address
- Patterns to apply
- Metrics to improve
-
Ensure Test Safety
- Verifies tests exist
- Adds missing tests if needed
- Ensures tests are comprehensive
-
Plan Incremental Changes
- Breaks into small, safe steps
- Orders changes by dependencies
- Plans verification after each step
Step 3: Execute Refactoring
Section titled “Step 3: Execute Refactoring”-
Make Small Changes
- One refactoring at a time
- Maintains behavior at each step
- Keeps code working continuously
-
Run Tests After Each Change
Terminal window # Pythonpytest -v# TypeScriptpnpm test -
Commit Incrementally
- Commits after each successful refactoring
- Makes rollback easy if needed
- Documents what changed and why
Refactoring Types
Section titled “Refactoring Types”Extract Function/Method
Section titled “Extract Function/Method”When: Code duplication or long methods
// Beforefunction processUser(user: User) { if (!user.email || !user.email.includes('@')) { throw new Error('Invalid email'); } if (user.name.length < 2) { throw new Error('Name too short'); } // ... more logic}
// Afterfunction processUser(user: User) { validateUser(user); // ... more logic}
function validateUser(user: User) { validateEmail(user.email); validateName(user.name);}
function validateEmail(email: string) { if (!email || !email.includes('@')) { throw new Error('Invalid email'); }}
function validateName(name: string) { if (name.length < 2) { throw new Error('Name too short'); }}Simplify Conditionals
Section titled “Simplify Conditionals”When: Complex nested if statements
// Beforeif (user) { if (user.isActive) { if (user.subscription) { if (user.subscription.isPaid) { return true; } } }}return false;
// Afterreturn user?.isActive && user?.subscription?.isPaid ?? false;Replace Magic Numbers
Section titled “Replace Magic Numbers”When: Unexplained numeric literals
# Beforedef calculate_discount(price): if price > 100: return price * 0.9 return price
# AfterDISCOUNT_THRESHOLD = 100DISCOUNT_RATE = 0.1
def calculate_discount(price): if price > DISCOUNT_THRESHOLD: return price * (1 - DISCOUNT_RATE) return priceImprove Naming
Section titled “Improve Naming”When: Unclear variable/function names
// Beforefunction calc(x: number, y: number): number { const z = x * y * 0.2; return z;}
// Afterfunction calculateTax(subtotal: number, quantity: number): number { const TAX_RATE = 0.2; const totalBeforeTax = subtotal * quantity; return totalBeforeTax * TAX_RATE;}Remove Dead Code
Section titled “Remove Dead Code”When: Unused functions, commented code
# Beforedef old_function(): # Not called anywhere pass
def current_function(): # result = old_way() # Old implementation result = new_way() return result
# Afterdef current_function(): result = new_way() return resultExtract Class/Module
Section titled “Extract Class/Module”When: Too many responsibilities in one class
// Beforeclass User { name: string; email: string;
validateEmail() { /* ... */ } sendEmail(subject: string, body: string) { /* ... */ } formatEmailTemplate(template: string) { /* ... */ }}
// Afterclass User { name: string; email: string;
validateEmail() { /* ... */ }}
class EmailService { sendEmail(to: string, subject: string, body: string) { /* ... */ } formatTemplate(template: string, data: any) { /* ... */ }}| Flag | Description | Example |
|---|---|---|
--goal=[goal] | Refactoring objective | --goal=simplify |
--safe | Extra cautious, more test verification | --safe |
--aggressive | Larger refactoring steps | --aggressive |
--format=[fmt] | Output format (concise/detailed) | --format=concise |
--test-first | Generate tests before refactoring | --test-first |
Goal Options
Section titled “Goal Options”| Goal | Focus |
|---|---|
clean | Remove clutter, improve naming |
extract | Pull out reusable code |
simplify | Reduce complexity |
optimize | Improve performance |
patterns | Apply design patterns |
Flag Examples
Section titled “Flag Examples”# Simplify complex function/refactor --goal=simplify src/utils/validation.ts
# Extract with extra safety checks/refactor --safe --goal=extract src/services/user.ts
# Performance optimization/refactor --goal=optimize src/api/heavy-query.ts
# Clean up with tests first/refactor --test-first --goal=clean src/legacy/Examples
Section titled “Examples”Simplify Complex Logic
Section titled “Simplify Complex Logic”Input:
/refactor --goal=simplify src/services/auth.tsOutput:
## Refactoring Complete: src/services/auth.ts
### Changes Made1. Extracted `validateCredentials()` function2. Simplified nested conditionals using early returns3. Replaced magic numbers with named constants4. Improved variable names for clarity
### Before```typescriptfunction login(email, pwd) { if (email) { if (pwd) { if (pwd.length >= 8) { const u = db.find(email); if (u) { if (bcrypt.compare(pwd, u.pwd)) { return generateToken(u); } } } } } throw new Error('Invalid');}const MIN_PASSWORD_LENGTH = 8;
function login(email: string, password: string): string { validateCredentials(email, password);
const user = db.findByEmail(email); if (!user) { throw new AuthError('Invalid credentials'); }
const passwordMatches = bcrypt.compare(password, user.hashedPassword); if (!passwordMatches) { throw new AuthError('Invalid credentials'); }
return generateToken(user);}
function validateCredentials(email: string, password: string) { if (!email) { throw new ValidationError('Email required'); } if (!password || password.length < MIN_PASSWORD_LENGTH) { throw new ValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`); }}Metrics
Section titled “Metrics”- Cyclomatic complexity: 8 → 3
- Function length: 18 lines → 12 lines
- Nesting depth: 5 → 2
- All 12 existing tests passing
- No behavior changes
### Extract Reusable Code
**Input:**```bash/refactor --goal=extract src/components/UserList.tsxOutput:
- Identifies repeated patterns
- Extracts into reusable hooks/components
- Updates all usage sites
- Verifies tests still pass
Deliverables
Section titled “Deliverables”After running /refactor, you receive:
- Refactored Code - Improved implementation
- Before/After Comparison - Clear visual diff
- Metrics - Complexity, length, nesting improvements
- Test Results - Confirmation of unchanged behavior
- Commit Message - Describing the refactoring
Best Practices
Section titled “Best Practices”- Always Have Tests First - Never refactor untested code
- Small Steps - Make one change at a time
- Run Tests Frequently - After each change
- Commit Often - Easy rollback if something breaks
- Preserve Behavior - Never change what the code does, only how