Skip to content

Intro & Principles

Code rarely arrives clean. It grows under deadlines, gets patched by people who have since moved on, and accumulates clever shortcuts that nobody dares touch. Refactoring is the discipline that lets you reshape that code into something you can read and change again — without altering what it does for the user.

This first module is about the ideas behind the practice. The rest of the course is a catalog of specific moves, but moves without principles are just risky edits. By the end of these five lessons you will be able to say precisely what refactoring is, defend why it is worth your time, and follow a rhythm that keeps you safe while you do it.

Refactoring improves the internal structure of code without changing its external behavior.

Everything in this course hangs off that sentence. If you change what the program does — fix a bug, add a feature, alter an output — that is valuable work, but it is not refactoring. Keeping the two activities separate is what makes both of them safe.

Refactoring is not a single heroic rewrite. It is a tight loop of tiny, reversible steps, each one verified before you take the next. You spot a smell, make one small behavior-preserving change, run the tests, and commit. If the tests go red, you undo and try a smaller step. Then you do it again.

flowchart LR
  A["Spot a smell"] --> B["Make one<br/>small change"]
  B --> C["Run the tests"]
  C -->|green| D["Commit"]
  C -->|red| E["Undo,<br/>try smaller"]
  E --> B
  D --> A
The refactoring loop: smell, small step, test, commit, repeat

That loop is the heartbeat of everything that follows. Big, scary refactorings are just hundreds of these small safe steps strung together.

LessonWhat you will take away
What is refactoring?A precise, behavior-preserving definition and the “two hats” rule
Why and whenThe payoff, technical debt, the boy-scout rule, and when not to refactor
Small steps and testsThe loop in detail and why a test safety net makes it work
Reading code smellsThe triggers that tell you what to refactor and which move to reach for

Once you finish here, you are ready for the practical catalog, starting with Composing Methods.

What is the defining property of a refactoring?
What is the heartbeat rhythm of refactoring described in this module?
If a refactoring causes a test to go red, what is the recommended response?