Skip to content

♻️ 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 interface

Introduce 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 ​

  1. Ensure tests cover the current behavior
  2. Make one small change
  3. Run tests
  4. Commit
  5. Repeat

Boy Scout Rule ​

"Leave the code better than you found it."

Small improvements on every touch compound over time.

Pergame Knowledge Base