Clean Code and Refactoring
Writing code other people can read and change safely, and improving existing code without breaking it.
What is it?
Code is read far more often than it's written. Clean code is code a teammate (or you, six months later) can understand quickly and change without fear. It's less about rules and more about lowering the cost of the next change.
Key habits:
- Names that explain intent. elapsedSeconds beats t; isEligibleForRefund beats check. - Small, focused functions that do one thing at one level of detail. - Single responsibility: a module or class should have one reason to change. - DRY ("Don't Repeat Yourself") for knowledge, not for every similar-looking line. Sometimes a little duplication (WET, "Write Everything Twice") is better than the wrong abstraction. - Readability over cleverness. A clear loop beats a one-liner nobody can debug.
Refactoring is changing the structure of code without changing what it does. It's done in small steps (rename, extract function, inline, move), each verified by tests, so the program works after every step. Code smells are surface signs that a refactoring may be due: long functions, duplicated logic, long parameter lists, deep nesting, and classes that know too much about each other.
Explain like I'm 10
Clean code is a well-organised kitchen: labelled jars, tools where you expect them, one drawer per purpose. Anyone can cook there. Refactoring is reorganising that kitchen while the restaurant stays open: you move one shelf at a time and check nothing is missing before moving the next.
Examples
Before and after: names, extraction, guard clauses (JavaScript)
// Before
function proc(u, o) {
let t = 0;
if (u) {
if (u.active) {
for (const i of o) {
if (i.s !== "cancelled") t += i.p * i.q;
}
if (u.vip) t = t * 0.9;
}
}
return t;
}
// After
const VIP_DISCOUNT = 0.9;
function orderTotal(user, orders) {
if (!user || !user.active) return 0;
const subtotal = sumOfActiveOrders(orders);
return user.vip ? subtotal * VIP_DISCOUNT : subtotal;
}
function sumOfActiveOrders(orders) {
return orders
.filter((order) => order.status !== "cancelled")
.reduce((sum, order) => sum + order.price * order.quantity, 0);
}When DRY goes wrong: the premature shared abstraction (Python)
# Two functions looked similar, so they were merged behind flags...
def format_record(record, for_invoice=False, for_report=False, include_tax=True):
... # every caller's special case now lives here, tangled together
# ...when the knowledge was actually different and changes for different reasons.
def format_invoice_line(item): ...
def format_report_row(row): ...Duplication of knowledge (one business rule in two places) should be removed. Code that merely looks similar but represents different concepts is better left separate. The 'rule of three' says wait for the third occurrence before abstracting.
How it works
Common code smells and their usual refactorings
- Long function: Extract Function, Decompose Conditional
- Unclear name: Rename Variable/Function
- Duplicated logic: Extract Function, then reuse it
- Deep nesting: Guard Clauses, Extract Function
- Long parameter list: Introduce Parameter Object
- Magic numbers/strings: Replace with Named Constant
- Feature envy (a method uses another class's data more than its own): Move Function
- Switch on type repeated in many places: Replace Conditional with Polymorphism or a lookup table
- Large class with many responsibilities: Extract Class
The safe refactoring loop 1. Make sure the behaviour is covered by tests. If it isn't, write characterization tests that pin down what the code currently does. 2. Make one small structural change, ideally with an IDE's automated refactoring. 3. Run the tests. Green: commit or continue. Red: undo and take a smaller step. 4. Keep refactoring commits separate from behaviour changes so review is easy ("make the change easy, then make the easy change").
Single responsibility, concretely. Ask "who would ask for this to change?" If tax rules, PDF layout and email delivery all live in one class, three teams' requests collide in it. Splitting along those lines keeps changes local.
Readability over cleverness. Prefer explicit over implicit, one idea per line, consistent conventions, and comments that explain why (a constraint or trade-off), not what the code already says.
Safe refactoring loop:
+--> tests green? --no--> add characterization tests
| |
| yes
| v
| small structural change (rename / extract / move)
| |
| v
| run tests --red--> revert, take a smaller step
| |
| green
| v
+--- commit, repeat until the code is easy to change
Then, separately: make the behaviour change.Why does it exist?
Most of a program's cost comes after it's first written: fixing bugs, adding features, onboarding new people. Messy code makes every one of those slower and riskier, and the slowdown compounds (technical debt). Refactoring exists because nobody gets the design right the first time; requirements change, and the code must be reshaped continuously to stay easy to change.
When to use it
- Before adding a feature to code that's hard to change: refactor first, then add the feature. - During code review, when a name or structure confuses the reviewer; confusion is the signal. - After getting something working: the "make it work, make it right" step. - When you touch a file anyway (the "boy scout rule": leave it a little better than you found it), as long as the change stays small and related.
When not to use it
- Don't refactor code without tests unless you add characterization tests first or the change is a purely mechanical, tool-assisted rename. - Don't mix large refactors with behaviour changes in one commit or PR; it hides bugs and makes review nearly impossible. - Don't rewrite stable, rarely touched code just because it's ugly; the value of clean code is in code that changes. - Don't extract abstractions after seeing a pattern only once or twice; wait until the shape is clear. - Close to a deadline or release freeze, prefer the minimal fix and schedule the cleanup.
Common mistakes
Over-applying DRY: merging code that only looks alike into one function full of flags, coupling unrelated features.
Splitting code into so many tiny functions and files that following one behaviour means jumping across ten places.
Refactoring and changing behaviour in the same step, so when a test fails you can't tell which change caused it.
Writing comments that restate the code (
i++ // increment i) instead of explaining why a non-obvious choice was made.Optimizing for cleverness (dense one-liners, obscure language features) over clarity for the next reader.
Practice exercises
- Easy:
Take a 40+ line function from a project you know and list every code smell you can find. For each, name the refactoring you'd apply.
- Medium:
Write characterization tests for an untested function with messy logic (for example a price calculator full of nested ifs), then refactor it with guard clauses, extracted functions and named constants, keeping all tests green after each step.
- Hard:
Find a class in an open-source project with several responsibilities. Plan a sequence of small, independently mergeable refactoring commits that splits it, describing what tests protect each step. Then carry out the first three steps.
Interview questions
What is refactoring?
Changing the internal structure of code without changing its observable behaviour, in small, verifiable steps, to make it easier to understand and modify. If behaviour changes, it's not a refactoring.
Why are tests important for refactoring?
They're the evidence that behaviour hasn't changed. With fast tests you can take small steps and know immediately if one broke something. Without them, refactoring is just editing and hoping.
What is a code smell? Give examples.
A surface symptom that often indicates a deeper design problem, not a bug in itself. Examples: long functions, duplicated logic, long parameter lists, deep nesting, magic numbers, feature envy, shotgun surgery (one change touches many files), and god classes.
Explain DRY vs WET, and when duplication is acceptable.
DRY means every piece of knowledge has one authoritative representation; it's about rules and decisions, not similar-looking code. Duplication is acceptable when similar code represents different concepts that will change for different reasons; merging them creates coupling. The 'rule of three' suggests abstracting on the third occurrence.
What is the Single Responsibility Principle?
A module should have one reason to change, meaning it serves one actor or concern. Mixing concerns (business rules, persistence, formatting) means unrelated changes collide in the same code and break each other.
What makes a good name?
It reveals intent and is specific: what the thing is or does and, for booleans, the question it answers (isExpired). It uses domain vocabulary, avoids abbreviations and noise words (data, manager, info), and its length scales with scope.
What are characterization tests?
Tests written against existing, often legacy, code to record what it currently does, right or wrong, so you can refactor safely. You call the code with representative inputs and assert on the actual outputs.
How do you refactor a large legacy codebase with no tests?
Pick the area you need to change, add characterization tests around it (finding or creating seams to isolate dependencies), use automated IDE refactorings for the riskiest mechanical steps, and improve incrementally alongside feature work. Avoid big-bang rewrites; consider the strangler-fig approach for replacing whole subsystems.
When should you not refactor?
When code is stable and rarely touched, when there are no tests and adding them isn't feasible right now, close to a release when risk must be minimal, or when a rewrite is genuinely planned. Refactor where change is happening.
How do you balance clean code against delivery speed?
Treat cleanliness as a means to faster future changes, not an end. Keep refactors small and tied to the work at hand, separate them into their own commits, take on deliberate technical debt with a note and a plan, and avoid gold-plating code that may be thrown away.