Published: Last updated:

Refactoring

Refactoring is the improvement of a codebase's internal structure without changing its external behaviour. It is not a feature, a bug fix, or a rewrite — it is a discipline of continuous code stewardship that prevents technical debt from becoming a system collapse.

Without regular refactoring, code ossifies: new features become increasingly expensive, bugs more frequent, and developers more frustrated.

Core Principles

  • Boy Scout Rule: Always leave the code slightly cleaner than you found it.
  • Red-Green-Refactor: In the TDD cycle, refactoring always follows green tests, never precedes them.
  • Small Steps: Large refactoring leaps without tests end in works-on-my-machine disasters. Small, test-secured steps are better.
  • No Behaviour Change: The public behaviour remains identical. If something breaks, it was not refactoring.

Common Refactoring Patterns

  • Extract Method: Moving a code block into a named function.
  • Rename: Naming variables, classes, and methods so they clearly express their intent.
  • Move Feature: Shifting logic to the object that owns the data.
  • Replace Conditional with Polymorphism: Replacing if-else cascades with object hierarchies.
  • Strangler Fig: Incrementally replacing legacy modules with new code (see Strangler Fig Pattern).

Focus: Continuous, Not Campaign-Based

Refactoring as a one-off large project almost always fails. As a daily habit within every story, it is cheap and effective.

FAQ

Can we create separate tickets for refactoring?

Small refactorings are done inline. Larger structural changes are planned as separate tasks in the backlog, with a clear justification (Enables Feature X, Reduces bug risk in module Y).

How do we justify refactoring to the business?

Show the direct connection: this refactoring reduces the time to build Feature X from two weeks to three days. Technical debt has real opportunity costs.

Reference Guide

  • Refactoring (Fowler): The definitive work. refactoring.com
  • Working Effectively with Legacy Code (Feathers): Refactoring without tests. O'Reilly
  • Refactoring Catalog: A complete collection of patterns. refactoring.guru

Related Topics