# Code Refactoring

> Improve code structure without changing external behavior.

## When to Use
- Code smell detected (duplication, long functions, deep nesting)
- "Clean this up" / "refactor this"
- Before adding new features to messy code

## Approach
1. **Ensure tests exist first** — never refactor without a test safety net
2. **Small steps** — one refactoring at a time, commit between each
3. **Run tests after every change** — refactoring should never break tests
4. **Extract, don't rewrite** — extract methods/classes from existing code rather than rewriting from scratch

## Common Refactorings
- **Extract method** — long function → smaller named functions
- **Extract class** — class doing too much → split by responsibility
- **Replace magic numbers** — `86400` → `SECONDS_PER_DAY = 86400`
- **Simplify conditionals** — deep if/else → early returns or lookup tables
- **Remove duplication** — DRY, but only for true duplication (same reason to change)
- **Rename for clarity** — `d` → `days_since_last_access`

## When NOT to Refactor
- No tests exist and you can't add them quickly
- You're about to ship and the code works
- The "mess" is actually just unfamiliar code that works correctly
