Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 50 ยท Software Design

Technical Debt and Refactoring

Understand technical debt, common code smells and how to refactor safely with tests, plus when a rewrite is justified, with a runnable before and after example.

Almost every codebase gets harder to change as it grows. Features are added under deadline pressure, requirements shift, and early design decisions stop matching reality. The result is code that works but resists change: small edits take days, and every fix creates a new bug somewhere else. Technical debt is the name for this accumulated cost, and refactoring is the main tool for paying it down.

This lesson covers what debt is, how to recognize it through code smells, how to refactor without breaking things, and how to decide when the answer is a rewrite instead. The examples are runnable JavaScript, with a small test harness, so you can see behavior preserved across a refactoring.

What technical debt is

The metaphor was coined by Ward Cunningham. Taking a shortcut is like borrowing money: you get something sooner (a feature shipped) and pay interest afterward (extra effort on every later change in that area). You can also pay down the principal by fixing the shortcut. Debt is not automatically bad; borrowing to hit an important date can be a sound decision. It becomes harmful when you do not know you have it, or when the interest grows until it consumes the team.

Kinds of technical debt

Deliberate A known shortcut taken for a reason, ideally recorded.
Accidental Poor design nobody noticed at the time.
Bit rot Code that aged as the world around it changed.
Knowledge debt Missing tests, docs or people who understand it.

The metaphor fits because unpaid interest compounds.

1 / 2

Debt also lives outside code: outdated dependencies, brittle build scripts, missing monitoring, and architecture that no longer fits the product are all debt. When a shortcut is deliberate, write it down as part of an architecture decision with a trigger for repaying it. The honest part of the metaphor is that messy code is not the same as debt: untidy code that nobody ever needs to change costs nothing. Interest is only paid where you work.

Code smells

A code smell is a surface sign that something deeper may be wrong. It is a hint, not a proof. Martin Fowler popularized the term in his refactoring catalog. Common ones:

Smell What it looks like Typical cure
Long function One function that does many steps Extract smaller functions
Duplicated code The same logic pasted in several places Extract and reuse
Large class / god module A module that knows and does too much Split by responsibility
Long parameter list Many arguments, often the same ones together Group them into an object
Magic numbers Unexplained literals like 0.08 Give them named constants
Feature envy A function mostly uses another module's data Move it next to the data
Shotgun surgery One change forces edits in many places Gather the scattered logic
Deep nesting if inside if inside if Early returns, extraction
Dead code Code that nothing calls Delete it (version control remembers)
Primitive obsession Everything is a string or number Introduce small types

Smells connect directly to cohesion and coupling: long functions and god modules are low cohesion; shotgun surgery and feature envy are high coupling.

Refactoring: change structure, keep behavior

Refactoring means restructuring existing code without changing what it does. The definition matters: if behavior changes, it is not refactoring, it is a modification. Keeping those two activities separate is the single most important discipline. Do not fix a bug and reorganize code in the same step, because when something breaks you will not know which change caused it.

Refactoring is only safe when you can prove behavior did not change, and that means tests. The recommended workflow is:

  1. Make sure tests exist for the code you will touch. If they do not, first write characterization tests: tests that record what the code does today, even if you think it is wrong, so you can see if it changes.
  2. Make one small change: rename, extract a function, move a method.
  3. Run the tests. Green means behavior is preserved; red means undo and try a smaller step.
  4. Commit often, so every step is easy to revert.
  5. Repeat. Many tiny safe steps beat one heroic rewrite.

Modern editors automate many refactorings (rename, extract, inline), which are safer than doing them by hand. Pair this with test-driven development: the third step of its red-green-refactor loop is exactly this activity.

Before and after, with tests

Here is a small function with several smells: magic numbers, nested conditions and mixed responsibilities. Its behavior is pinned down first by a tiny test harness. Run it, and note that all the tests pass.

JS Before: characterization tests on messy code

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The tests give a safety net. Now refactor in small steps: name the rates, split the domestic and international rules into functions, and flatten the nesting with early returns. The tests are unchanged and must give the same result.

JS After: the same behavior, clearer structure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both versions report the same result. The second is not shorter, but it names its numbers, has no nesting deeper than one level, and each rule can be read and changed in one place: adding a new country group no longer means threading a new branch through a deep if tree. The original code had a dormant question that the tests would also now surface: should a shipment of exactly 5 kg be "medium"? The characterization tests simply recorded what it did. If that behavior is a bug, fix it in a separate commit, with its own test change, not hidden inside the refactoring.

Measuring and managing debt

You cannot manage what nobody sees. Teams use several signals: where changes are slow, which files change most often together, which modules produce the most bugs, and static-analysis reports on complexity and duplication. Combine how bad a piece of code is with how often it changes: ugly code in a stable corner is low priority, and moderately ugly code that every feature touches is high priority.

Practical ways to pay debt down without stopping the product:

  • The boy-scout rule: leave the code a little cleaner than you found it, in small steps with each change.
  • Make it visible: keep a debt list with the cost of each item, and review it when planning.
  • Reserve capacity: set aside a steady share of each iteration (many teams use roughly 10 to 20 percent) for improvement work, rather than waiting for a "cleanup sprint" that never comes.
  • Refactor around the feature: "make the change easy, then make the easy change". Restructure the area just enough that the new feature fits naturally.

When to rewrite

The tempting alternative to refactoring is to throw everything away and start over. A rewrite sounds clean, but it is among the riskiest decisions in the field. The old system contains years of fixes for strange real-world cases that nobody documented; a rewrite must rediscover each one, usually in production, while the old system still needs maintenance. Rewrites routinely take far longer than planned and deliver less than hoped.

A rewrite can still be right when the technology is truly dead (no one can hire for it, no security updates), when the architecture fundamentally cannot meet a new core requirement, or when the system is small enough that rebuilding is cheaper than understanding. Even then, prefer the strangler fig approach: build the replacement alongside, move one capability at a time behind a common interface, and retire pieces of the old system as they become unused. That keeps the product working throughout and lets you stop if the plan proves wrong. See deployment, maintenance and software evolution for how systems age.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement best defines refactoring?

    If behavior changes, it is a modification. Refactoring keeps behavior identical and improves structure.
  2. 2. Why should tests exist before you refactor?

    Tests, including characterization tests, are the safety net that tells you immediately whether a step broke something.
  3. 3. Which is an example of a code smell?

    Duplicated code is a classic smell: every fix must be repeated in each copy, and the copies drift apart.
  4. 4. Which technical debt deserves attention first?

    Interest is paid where you work. Prioritize by how bad the code is combined with how often it changes.
  5. 5. What is the safer alternative to a full rewrite called in the lesson?

    You build the replacement next to the old system and move one capability at a time, so the product keeps working throughout.

Summary

  • Technical debt is the extra cost of change caused by shortcuts and aged design; it accrues interest where you keep working.
  • Debt can be deliberate or accidental, and it also exists in tests, docs, tooling and dependencies.
  • Code smells such as long functions, duplication and magic numbers hint at deeper design problems.
  • Refactoring changes structure but not behavior; do it in small steps under tests and keep it separate from bug fixes.
  • Prioritize debt by severity and by how often the code changes; reserve steady capacity to pay it down.
  • Prefer incremental replacement (strangler fig) over big rewrites, which are risky and often disappoint.

Next: Agile Principles and Manifesto.