β»οΈ Refactoring Patterns β
Improving code structure without changing behavior.
When to refactor β
- Before adding a new feature to messy code
- After getting a feature working (clean up)
- When you see repeated patterns across the codebase
- When code is hard to test
- During dedicated tech debt sprints
When NOT to refactor β
- Code that works and won't be touched again
- Right before a critical deadline
- Without tests to verify behavior is preserved
- Just because it's "not how you'd write it"
Common refactoring moves β
Extract function β
Pull a block of code into a named function.
// Before: 20 lines of inline logic
// After: processPayment(order)Extract variable β
Give a complex expression a meaningful name.
typescript
// Before
if (user.age >= 18 && user.hasConsent && !user.isBanned) { ... }
// After
const canAccessService = user.age >= 18 && user.hasConsent && !user.isBanned
if (canAccessService) { ... }Replace conditional with polymorphism β
typescript
// Before: switch on type everywhere
// After: each type implements a common interfaceIntroduce parameter object β
typescript
// Before
function search(query, page, limit, sortBy, order) { ... }
// After
function search(params: SearchParams) { ... }Remove dead code β
If it's not called, delete it. Git has the history.
Safe refactoring process β
- Ensure tests cover the current behavior
- Make one small change
- Run tests
- Commit
- Repeat
Boy Scout Rule β
"Leave the code better than you found it."
Small improvements on every touch compound over time.