Lesson 7 of 28Keeping code healthy
Code Smells and Refactoring
Name the smell, pin the behaviour, change structure in tiny green steps, and move large codebases without a rewrite.
The Principles unit gave you rules for writing new code well. Most working days start in code someone else wrote. Your first ticket at a new job says "add a platinum tier to invoicing". You open invoice() and find 80 lines, six arguments, three nested if chains, and no tests. Two people have left since it was written. The change itself is one line, but you cannot tell which line, or what else it will break. This is the normal state of code that makes money, and the skill that separates a junior from a senior here is not writing clean code from scratch. It is changing messy code safely, in small steps, while the business keeps running.
The Clean Code lesson gave you the short version: a smell table and a "pin, change, rerun" loop. This lesson goes far deeper: the full family of smells, the refactorings that fix them, how to work on code with no tests at all, and how to move a whole codebase without a big-bang rewrite.
Smells come in four families
A code smell is a surface symptom that usually points to a design problem. It is not a bug. The code works. The smell tells you where the next change will hurt. Martin Fowler's Refactoring (2nd edition, 2018, with examples in JavaScript) catalogues dozens. They group into four families, and knowing the family tells you the kind of fix.
| Family | Smell | What you see |
|---|---|---|
| Bloaters | Long function | 80 lines with # step 3 comments |
| Large class | OrderManager with 40 methods and 25 fields | |
| Long parameter list | invoice(c, items, code, ctry, exp, notes) | |
| Primitive obsession | Money as float, email as str, status as "pd" | |
| Data clumps | street, city, postcode always travel together | |
| Change preventers | Divergent change | One class edited for tax rules, PDF layout and email copy |
| Shotgun surgery | Adding a tier means editing 9 files | |
| Couplers | Feature envy | A method that mostly reads another object's fields |
| Message chains | order.customer.account.billing.address.city | |
| Middle man | A class whose methods only forward to another class | |
| Dispensables | Dead code | A function nothing calls, kept "just in case" |
| Speculative generality | A plugin system with exactly one plugin | |
| Duplicate code | The same discount rule in the API and in a cron job |
Two of these confuse people. Divergent change is one module that changes for many reasons (it violates single responsibility). Shotgun surgery is the mirror image: one reason to change touches many modules (the knowledge is scattered). The fix for the first is to split. The fix for the second is to gather.
Match each symptom to the smell it shows.
The refactoring catalogue you will actually use
A refactoring is a named, small change to structure that keeps behaviour identical. The names matter: in a code review, "extract function, then move it to Customer" is a precise instruction, and your IDE can perform several of them automatically.
| Refactoring | Fixes | In one line |
|---|---|---|
| Extract function | Long function | Pull a block out and name it after what it does |
| Inline function / class | Middle man, speculative generality | Put the body back where it is used and delete the wrapper |
| Rename | Every smell, eventually | Make the name match current understanding |
| Introduce parameter object | Long parameter list, data clumps | Group values that travel together |
| Replace primitive with value object | Primitive obsession | Money, Email, OrderStatus instead of float and str |
| Replace conditional with polymorphism | Repeated if type == | A class per case, or in Python and TS a dict of functions |
| Move function | Feature envy | Put behaviour next to the data it uses |
| Split phase | Function that parses and computes | Phase 1 builds a clean structure, phase 2 works on it |
| Encapsulate collection | Callers mutate your list | Return a copy and expose add / remove |
Split phase deserves a word. Most tangled functions mix two jobs: turning raw input into something meaningful, and doing the calculation. Separate them with an intermediate data structure and each half becomes simple. Compilers work this way (parse, then generate), and so do good request handlers.
Two value-object refactorings in TypeScript. Money stores integer cents so arithmetic is exact, and refuses to add pounds to euros. Basket encapsulates its collection, so a caller cannot push 500 lines past the limit by reaching into the array.
Press Run (⌘ Enter) to see what happens.The 0.1 + 0.2 line is why primitive obsession with money is a real bug and not a style point. Once the value object exists, every rule about money (rounding, currency checks, formatting) has one home instead of fifty.
The safe loop, and the golden master
The rule is green, tiny step, green, commit. Start with passing tests. Make one change you can name. Run the tests. Commit. If anything goes red, you know exactly which step did it, and git checkout . costs you two minutes, not an afternoon.
Prefer your IDE's automated refactorings (rename symbol, extract method, move to file) over hand edits. They update every call site, including ones you would miss with search and replace, like a method called through a variable. They are not magic: dynamic Python (getattr(obj, name)) and string-based lookups can hide uses the tool cannot see, so the tests still run.
But what if there are no tests? You write a characterization test (Michael Feathers' term): a test that records what the code does today, not what it should do. For a calculation like invoice(), the fastest version is a golden master: run a large grid of inputs through the old code, save every output, and require the new code to produce the identical list. You do not need to understand the code to write it, which is the point.
Here is the smelly invoice() and a refactored version: a value type for lines, a dict of discount functions instead of an elif chain, named constants, and split phase. The golden master proves 144 combinations still match.
Press Run (⌘ Enter) to see what happens.Now break it on purpose. Change the "DE" rate to 0.2 and run again: the fingerprints differ and the assert fires. That is the safety net working. Next change SMALL_ORDER_LIMIT to 40. It passes, because no basket in the grid totals between 40 and 50. A golden master only protects the inputs you gave it. Finally, try "simplifying" total - total * 0.2 to total * 0.8 in _save20. It passes here, but only because the final round hides a last-bit difference. Algebra that is true for real numbers is not always true for floats, so a cleanup like this is only safe because the golden master proved the observable output did not move.
What does this print?
t = 33.3 print(t - t * 0.2 == t * 0.8)
A golden master has limits. It pins bugs as faithfully as features, so when a case looks wrong, write it down and fix it in a separate commit after the refactor. And, as the SMALL_ORDER_LIMIT experiment showed, it only covers the inputs in your grid. Build the grid from real production-shaped data plus the values on each side of every boundary you can see in the code (49.99 and 50, 100 and 100.01, empty, zero). Coverage tools help here: if a branch never runs during the golden master, the grid is missing a case.
Legacy code without tests
Feathers' book Working Effectively with Legacy Code (2004) defines legacy code bluntly: code without tests. His core problem is the chicken-and-egg: to refactor safely you need tests, and to add tests you often need to refactor (because the code calls the real clock, the real database, the real email server).
His answer is the seam: a place where you can change what the code does without editing it there. In Python and TypeScript the cheapest seams are a parameter with a default (now=None), a function passed in, or a module attribute you can patch in a test. Find or create one seam with the smallest possible edit, get the code under test, then refactor properly.
When you must add behaviour to code you cannot yet test, two techniques keep the risky part small:
- Sprout method: write the new logic as a new function, fully tested, and add a single call to it from the legacy code. The untested code changes by one line.
- Wrap method: rename nothing inside the old function. Write a new function that does the new work before or after calling the old one, and point callers at the wrapper. Good for audit logs, metrics and permission checks.
Press Run (⌘ Enter) to see what happens.checkout() today. Which approach keeps the risk lowest?Moving big things: expand, migrate, contract
Renaming a local variable is one commit. Changing a function signature used in 200 places, or swapping an ORM, is not. Large-scale refactoring needs techniques that keep main releasable the whole time.
Expand
Add the new alongside the old
`get_orders(account_id=...)` is added. The old `customer_id` keyword still works and forwards to the new code. Nothing breaks. Ship it.
Migrate
Move callers in small batches
Update call sites a module at a time, each in its own reviewable PR. Log a deprecation warning when the old keyword is used so you can see who is left.
Verify
Prove nobody uses the old path
The warning count in logs drops to zero. A search and a type check find no remaining callers, including in other repos.
Contract
Delete the old path
Remove `customer_id` support in one small commit. If you skip this step, you have not refactored, you have added a second API.
Parallel change (also called expand and contract) works for function signatures, database columns, API fields and config keys. The same shape appears in zero-downtime database migrations.
Branch by abstraction is parallel change for a whole component. To replace an old PDF library: introduce an interface the callers use, make the old library implement it, move every caller to the interface, build the new implementation behind it, switch over (often with a feature flag), then delete the old one. No long-lived branch, no merge from hell.
The Mikado method helps when a change keeps snowballing. Try the goal change naively. When it breaks things, note each prerequisite as a node in a graph, then revert. Pick a leaf prerequisite, do it on clean code, commit. Repeat until the goal itself is a leaf.
You try the move directly. Imports explode. You write down what broke, then revert everything.
When the same mechanical edit must happen in 400 files, write a codemod: a program that edits code through its syntax tree, not regex. jscodeshift and ts-morph do this for JavaScript and TypeScript, LibCST for Python (it keeps comments and formatting), and ast-grep works across many languages with pattern rules. Run it, review a sample of the diff, and let the tests and type checker review the rest.
Put a branch-by-abstraction replacement of an email vendor in order.
- Tap the steps below in the right order.
Refactor or rewrite?
Every team eventually hears "this is unfixable, let's rewrite it". Rewrites usually fail for the same reasons. The old code contains years of bug fixes and edge cases that nobody wrote down. The business will not freeze features for a year, so the new system chases a moving target. And nothing ships until the end, so you get no feedback and no value along the way. Joel Spolsky's 2000 essay on Netscape is still the classic warning.
The alternative is the strangler fig applied at code level. New behaviour goes into new, clean modules. Old paths are moved over one route, one report or one use case at a time, behind the same interface, until the old module has no callers and can be deleted. You saw the service-level version in Monolith vs Microservices; the same idea works inside one codebase. A rewrite can still be right for something small and well understood, or when the platform itself is dead. Make it earn that decision with a written comparison, not frustration.
Make refactors easy to review
Never mix a refactor with a behaviour change in one commit. A reviewer can check "pure rename, 40 files" in a minute, and "one rule changed, 3 lines" in another. Mixed together, they have to read 43 files with suspicion. The habit Kent Beck summarises as "make the change easy, then make the easy change" applies to commits too: first the refactor commit, then the feature commit.
For big mechanical commits (a formatter run, a codemod), add the commit hash to a .git-blame-ignore-revs file so git blame skips it. GitHub honours this file automatically, and locally you set git config blame.ignoreRevsFile .git-blame-ignore-revs.
- characterization test
- A test that records what code does today, right or wrong, so a refactor cannot change it unnoticed.
- golden master
- A characterization test that runs many inputs through the old code and requires identical outputs from the new code.
- seam
- A place where you can change behaviour without editing the code there, such as an injectable parameter.
- sprout method
- Adding new behaviour as a new tested function, with one call from the legacy code.
- parallel change
- Expand, migrate and contract: add the new form beside the old, move callers, then delete the old.
- branch by abstraction
- Replacing a component by putting an interface in front of it, building the new implementation behind it, then switching.
- shotgun surgery
- A smell where one logical change forces edits in many modules.