Course contentsShow
← Software Engineering
Lesson 363 of 1,93310. RefactoringFree lesson

Opportunistic vs Planned Refactoring

When to refactor as part of feature work versus scheduling dedicated refactoring time for larger improvements.

Opportunistic vs Planned Refactoring

What you'll learn: You'll understand when to refactor "in the moment" while building features versus scheduling dedicated time for larger refactoring efforts.

The Core Idea

Refactoring happens in two main contexts. Opportunistic refactoring means you clean up code while doing feature work—you're adding a function and notice messy code nearby, so you tidy it up before continuing. Planned refactoring means you schedule dedicated time specifically to improve code structure, often for larger improvements that can't be done in small increments.

Opportunistic Refactoring: The Boy Scout Rule

Think of this as "leaving the campsite cleaner than you found it." You're implementing a feature, encounter a Long Method or Duplicate Code, and refactor it right then. This is the preferred approach because:

  • Refactoring happens naturally as part of understanding code
  • Improvements are small and safe
  • No separate schedule needed
  • Keeps the codebase continuously improving

Most refactoring should be opportunistic—done invisibly as part of regular work.

Planned Refactoring: The Deliberate Investment

Sometimes you need dedicated time for larger restructuring:

  • Addressing Change Preventers that affect multiple features
  • Extracting Classes from God Objects
  • Major architectural improvements
  • Technical debt accumulated in neglected areas

Think of this like scheduled home renovation versus tidying as you go. It's more disruptive but sometimes necessary for big improvements.

The Balance

The best teams minimize planned refactoring by doing opportunistic refactoring religiously. If you're constantly scheduling refactoring sprints, it often means you're not refactoring enough during feature work. However, some planned refactoring is inevitable—the key is making it the exception, not the rule.

Key Takeaway: Refactor opportunistically as part of everyday feature work whenever possible; reserve planned refactoring sessions only for larger structural improvements that can't be done incrementally.