---
description: Refactor code while keeping tests green (optional)
---

# REFACTOR Phase: Improve Code Quality

You are entering the REFACTOR phase. Your task is to improve code quality while keeping all tests GREEN.

## Instructions

1. **Read CLAUDE.md** to understand:
   - Project coding standards
   - Preferred patterns and conventions
   - When to refactor vs when to leave it

2. **Ensure tests are GREEN** before starting
   - Run tests first: `/test`
   - Don't refactor if any tests are failing

3. **Look for code smells**:
   - Duplication (rule of three)
   - Long methods/functions
   - Complex conditionals
   - Unclear names
   - Too many parameters
   - Large classes with too many responsibilities

4. **Improve incrementally**:
   - Make one small change at a time
   - Run tests after each change
   - Stop if tests turn RED and revert

5. **Run tests frequently** using project's test command

6. **Update TODO.md** if refactoring reveals new work

## Common Refactorings

### Extract Method/Function
If a method is doing too much, break it into smaller pieces.

### Extract Class
If a class has too many responsibilities, split it.

### Rename
If names are unclear, rename them (variables, methods, classes).

### Remove Duplication
If you see the same code in 3+ places, extract it.

### Simplify Conditionals
Replace complex if/else with early returns, guard clauses, or polymorphism.

## What NOT to Do

❌ **Don't add new features** - that's for RED/GREEN phases
❌ **Don't change behavior** - tests should still pass unchanged
❌ **Don't optimize prematurely** - only if there's a measured problem
❌ **Don't refactor without tests** - tests must be GREEN first
❌ **Don't refactor if unclear** - ask for clarification first

## Process

1. Identify code smell
2. Plan refactoring approach
3. Make one small change
4. Run tests (see CLAUDE.md for command)
5. If GREEN, continue or commit
6. If RED, revert and try different approach

## After Refactoring

Once satisfied with code quality:
- All tests still GREEN
- Code is cleaner and more maintainable
- Follow commit message format from CLAUDE.md
- Move to `/next` feature
