Refactoring Techniques: A Complete Guide
Master the essential refactoring techniques, from extract method and move function to guard clauses and polymorphism, plus a safe workflow and when not to refactor.
Introduction
Refactoring is changing the internal structure of code without changing what it does. That second half is the part people forget: if you’re altering behavior (fixing a bug, adding a feature), you’re not refactoring, you’re changing code, and the safety rules are different.
Done well, refactoring is how codebases stay readable years after they were written. Done badly, as big-bang rewrites dressed up as “cleanup”, it is how teams spend three months breaking things and calling it progress. The difference is almost never the technique itself; it’s whether you worked in small, tested steps or one giant leap of faith.
What follows is the workflow that makes refactoring safe, the handful of techniques that handle 90% of real cleanup (extract method, move function, extract class, rename, guard clauses, polymorphism, named constants), and, just as important, when not to refactor at all. The examples use JavaScript, but the techniques transfer to any language.
Quick answers:
- Refactoring means restructuring code without changing behavior; bug fixes and features are not refactoring.
- Only refactor against a green test suite; on legacy code, write characterization tests first.
- Pick the technique by the smell it fixes: long method → extract method, type-switching → polymorphism, deep nesting → guard clauses.
- Skip it when there’s no test net, the code is about to be deleted, or it lives outside your codebase boundary.
The Safe Refactoring Workflow
Every refactoring technique in this guide assumes the same workflow. Skip it and even a trivial rename becomes a coin flip.
The steps that matter:
- Understand before touching. Read the code, note what it actually does (not what the names claim it does). A rename of a misnamed function without understanding it just moves the lie around.
- Get tests in place first. If the code has none, write characterization tests (tests that pin down current behavior, including the weird parts) before you touch a line. This is non-negotiable for legacy code.
- One step at a time. A single extract method, a single rename. Each step should take minutes, not hours.
- Commit after every green step. Each green test run is a checkpoint you can return to.
git stashbeats archaeology when a step goes wrong. - Merge early. Long-lived refactoring branches diverge from main and turn merge day into a second project. Small commits, frequent merges.
The mental model is Kent Beck’s red-green-refactor loop applied to existing code: make it work, then make it right, but never both at once.
Reading the Smells
Refactoring is driven by smells: surface symptoms that tell you which technique to reach for. The table maps common smells to the technique that addresses them; the sections after it walk through each one.
| Smell | Technique | What it fixes |
|---|---|---|
| Method does too much | Extract Method | Readability, reuse |
| Logic buried in expressions | Extract Variable | Named intermediate steps |
| Method belongs to another class | Move Function | Cohesion, coupling |
| Class doing too many jobs | Extract Class | One job per class |
| Name lies about what code does | Rename | Comprehension |
| Type checks everywhere | Replace Conditional with Polymorphism | Extensibility |
| Deep nesting, arrow code | Guard Clauses | Linear flow, early exit |
| Bare numbers/strings in logic | Named Constant | Meaning, single source of truth |
If you learn only one thing from this guide: refactoring starts by naming the smell, not by picking a technique. “This method is long” is the observation; “extract method” is the response.
Extract Method
Extract Method is the most-used refactoring in the catalog: take a coherent chunk of a long method, give it a name that says what it does, and call it. Long methods hide their logic; short, well-named methods document themselves.
// Before: calculate() does three jobs
function calculate(order) {
let total = 0;
for (const item of order.items) {
total += item.price;
}
if (order.customer.isVip) {
total *= 0.9;
}
return total;
}
// After: each job gets a name
function calculate(order) {
return applyDiscount(subtotal(order), order.customer);
}
function subtotal(order) {
return order.items.reduce((sum, item) => sum + item.price, 0);
}
function applyDiscount(total, customer) {
return customer.isVip ? total * 0.9 : total;
}
The mechanics matter more than the example. Extract a chunk that is self-contained: a clear input and output, no hidden side effects on shared state. If the extracted method needs the whole local scope, you’re usually looking at a bigger problem (see Extract Class). Name the new method by what it accomplishes, not how it accomplishes it (subtotal, not calculateItemsSum).
A companion technique worth knowing: Extract Variable. When an expression does too much inline work, pull it into a named variable so the reader can see the steps.
// Before
const price = item.price * (1 - customer.discount) + item.price * taxRate;
// After
const discounted = item.price * (1 - customer.discount);
const tax = item.price * taxRate;
const price = discounted + tax;
And its inverse, Inline Method/Variable: when a method is just a one-line alias that adds a hop with no name value, inline it and delete the indirection. The skill is knowing which direction the code needs: clarity is a dial, not a destination.
Move Function
Move Function relocates a method to the object or module that owns the data it mostly works with. A method that reaches into another object for everything it needs is a method in the wrong place; that is the “feature envy” smell, and it is the reason classes drift apart over time.
// Before: Order reaches into Customer for everything
function discountFor(order) {
return order.customer.isVip ? 0.9 : 1.0;
}
// After: the function lives with the data it uses
class Customer {
get discountRate() {
return this.isVip ? 0.9 : 1.0;
}
}
// call site: customer.discountRate
The heuristic is simple: put behavior with the data it operates on. When a method mostly uses fields from another object, move it there; the code that stays behind gets smaller, and the code it joins gets more cohesive. The same logic applies at module level: a helper imported by only one file probably belongs in that file, not in a shared utils.js that becomes a junk drawer.
Extract Class
Extract Class is what you reach for when Extract Method isn’t enough: when the class itself has outgrown one responsibility. The tell is a class where some fields and methods form a coherent subgroup: address fields with address methods, pricing fields with pricing methods.
// Before: Employee owns personal data AND salary logic
class Employee {
constructor(name, salary, taxId) {
this.name = name;
this.salary = salary;
this.taxId = taxId;
}
annualSalary() { return this.salary * 12; }
taxRate() { /* ... */ }
}
// After: payroll logic gets its own class
class Employee {
constructor(name, payroll) {
this.name = name;
this.payroll = payroll;
}
}
class Payroll {
constructor(salary, taxId) {
this.salary = salary;
this.taxId = taxId;
}
annualSalary() { return this.salary * 12; }
taxRate() { /* ... */ }
}
The payoff is a class you can reason about and test independently: Payroll changes when compensation rules change, Employee doesn’t. The cost is one more level of indirection (employee.payroll.annualSalary()), which is worth it when the two responsibilities genuinely diverge and wasteful when they don’t. If callers keep reaching through the wrapper, delegate instead of exposing the inner object.
Rename
Rename sounds trivial and is the highest-ROI refactoring that exists: a name is documentation that updates itself, and most “confusing code” is just code with names that lie about it.
// Before
function calc(o) {
const t = o.items.reduce((s, i) => s + i.price, 0);
return o.customer.isVip ? t * 0.9 : t;
}
// After
function calculateDiscountedTotal(order) {
const subtotal = order.items.reduce((sum, item) => sum + item.price, 0);
return order.customer.isVip ? subtotal * 0.9 : subtotal;
}
The rules that make a rename stick: name functions and variables by what they do or hold (calculateDiscountedTotal, subtotal, isVip), not how (arr, tmp, data2). Keep names consistent: if the codebase says customer everywhere, don’t suddenly introduce client. The naming rules in the clean code guide apply here directly. And use your IDE’s rename refactoring, not find-and-replace, because the IDE knows the difference between order the variable and order the concept in a comment; find-and-replace doesn’t.
Replace Conditional with Polymorphism
When you keep switching on a type field (if (type === 'vip') in three places, switch in a fourth), the conditionals are telling you the types want to be objects. Replace Conditional with Polymorphism moves each branch into its own class behind a shared interface, and the switch evaporates.
// Before: every new customer type adds another branch
function priceFor(order) {
switch (order.customer.type) {
case 'vip': return subtotal(order) * 0.9;
case 'student': return subtotal(order) * 0.8;
default: return subtotal(order);
}
}
// After: each type carries its own pricing
class RegularCustomer { discountRate() { return 1.0; } }
class VipCustomer { discountRate() { return 0.9; } }
class StudentCustomer { discountRate() { return 0.8; } }
function priceFor(order) {
return subtotal(order) * order.customer.discountRate();
}
The benefit is open/closed behavior: a new customer type is a new class, not another edit to every switch in the codebase. The cost is indirection: simple cases (two branches, unlikely to grow) are often clearer left as a conditional. Reach for this when the same type-check appears in multiple places or the number of cases keeps growing; for a one-off if, it’s ceremony for ceremony’s sake.
Replace Nested Conditional with Guard Clauses
Nested ifs stack up until the happy path is six indents deep and the reader loses the thread. Guard clauses flip the logic: each edge case exits early, and the main logic runs at the top level.
// Before: the happy path is buried under nesting
function price(order) {
if (order.items.length > 0) {
if (!order.customer.isBlocked) {
let total = subtotal(order);
if (order.customer.isVip) {
total *= 0.9;
}
return total;
}
throw new Error('Customer is blocked');
}
throw new Error('Order has no items');
}
// After: failures exit early, the happy path flows
function price(order) {
if (order.items.length === 0) throw new Error('Order has no items');
if (order.customer.isBlocked) throw new Error('Customer is blocked');
let total = subtotal(order);
if (order.customer.isVip) total *= 0.9;
return total;
}
The transformation is mechanical (invert each condition and move the failure path to the top) and it changes how the code reads from “peel the onion” to “check the prerequisites, then do the work”. Guard clauses work best at the start of a method for preconditions; mid-method, prefer extracting the nested logic into a named method instead of stacking early returns everywhere.
Replace Magic Number with Named Constant
A bare 0.9 in the middle of a method means nothing to the next reader. Named constants give values meaning and give you a single place to change them.
// Before: what is 0.9?
total = total * 0.9;
if (status === 2) { /* ... */ }
// After
const VIP_DISCOUNT = 0.9;
const STATUS_SHIPPED = 2;
total = total * VIP_DISCOUNT;
if (status === STATUS_SHIPPED) { /* ... */ }
This is the cheapest readability win in the catalog: a five-second change that makes 0.9 self-documenting and centralizes the value when the discount rate inevitably changes. The same rule applies to status codes, thresholds, timeouts, and any string literal that carries meaning.
A Refactoring Session, Step by Step
The techniques click once you see them chained together on real code. Here is a messy function and the sequence of small, tested steps that cleans it up, in the same order you would use at the keyboard.
// The starting point: one method, four jobs, nesting, magic values
function processOrder(order) {
if (order != null) {
if (order.items.length > 0) {
let t = 0;
for (const i of order.items) { t += i.price * i.qty; }
if (order.customer.type === 'vip') { t = t * 0.9; }
if (t > 100) { t = t - 10; }
order.total = t;
return order;
}
}
throw new Error('Invalid order');
}
Step 1: guard clauses first. Before extracting anything, flatten the nesting so the happy path is visible:
function processOrder(order) {
if (order == null) throw new Error('Invalid order');
if (order.items.length === 0) throw new Error('Invalid order');
let t = 0;
for (const i of order.items) { t += i.price * i.qty; }
if (order.customer.type === 'vip') { t = t * 0.9; }
if (t > 100) { t = t - 10; }
order.total = t;
return order;
}
Tests still green? Commit. Step 2: extract the subtotal loop.
function processOrder(order) {
if (order == null) throw new Error('Invalid order');
if (order.items.length === 0) throw new Error('Invalid order');
let total = subtotal(order);
if (order.customer.type === 'vip') { total = total * 0.9; }
if (total > 100) { total = total - 10; }
order.total = total;
return order;
}
function subtotal(order) {
return order.items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
Green, commit. Step 3: named constants and a rename pass, because 0.9, 100, 10, and t all mean something:
const VIP_DISCOUNT = 0.9;
const FREE_SHIPPING_THRESHOLD = 100;
const SHIPPING_FEE = 10;
// rename: processOrder -> calculateOrderTotal, t -> total
Green, commit. Step 4: move the pricing decision to the customer: the function is reaching into order.customer.type for its own logic, which is feature envy:
class Customer {
discountRate() { return this.type === 'vip' ? VIP_DISCOUNT : 1.0; }
}
// call site: total = total * order.customer.discountRate();
Four techniques, four commits, and the function went from “read it three times” to “scan it once”, with a passing test suite the whole way through. That is the entire job: repeat this sequence in whatever corner of the codebase needs it, and stop when the code stops fighting you.
When Not to Refactor
Refactoring has a cost (time, review load, regression risk) and there are situations where it is the wrong spend:
- No tests and no time to write them. The workflow above is the safety net; without tests you’re not refactoring, you’re rearranging code and hoping. If you can’t afford characterization tests, you can’t afford the refactoring.
- The code is about to be deleted. A deprecated module or a feature on its way out doesn’t need polishing; leave it and spend the effort on code with a future. Technical debt management covers how to make that call.
- It is someone else’s stable API or a vendored dependency. The refactoring budget stops at your codebase boundary; wrapping is safer than editing.
- The problem is actually missing functionality. Refactoring preserves behavior; if the code is structurally fine but does the wrong thing, refactor after the fix, not before.
- Premature cleanup. Not every
ifneeds polymorphism and not every two-line method needs extraction. Some duplication is cheaper than the abstraction that removes it; the rule of three exists for a reason.
A useful heuristic for legacy code specifically: refactor in the path of work. When a bug fix or feature touches a messy area, clean the slice you are editing and leave the rest. Boy-scout rule, not renovation project.
Refactoring Legacy Code
Legacy code, the kind with no tests and names like processData2, needs a different posture than the greenfield examples above. The working sequence from Michael Feathers’ Working Effectively with Legacy Code:
- Find a seam. A seam is a place where you can change behavior without editing the code: a method call, a dependency injection point. Seams are where you introduce tests.
- Write characterization tests. Not “correct” tests: tests that document what the code does today, bugs included. Their job is a safety net, not a spec.
- Refactor in tiny steps. Extract small methods, introduce seams, rename, always with the characterization tests green.
- Grow the test net. Each step widens what the tests cover, which makes the next step safer.
The mistake to avoid is the big refactor sprint: two weeks of branch work, a merge conflict apocalypse, and behavior differences nobody can explain. Legacy cleanup pays off through many small, merged changes over time, which is also why it pairs so well with test-driven development for the new code around it.
Tooling
You do not have to do this by hand. Modern IDEs automate the mechanical transforms and eliminate the “renamed in 9 of 10 places” class of mistakes:
- Rename refactoring: semantic rename across files, strings, and references (VS Code, WebStorm, IntelliJ). Always use it instead of find-and-replace.
- Extract method/variable: IDE picks the right signature and call site automatically.
- Safe delete / move: checks usages before letting you remove or relocate code.
- Linters and formatters: ESLint, Prettier, ruff, and friends catch many mechanical smells before a human reads the code.
- Type checkers: a type error is the cheapest regression detector that exists; run it after every step.
Automated tools don’t choose what to refactor (that’s still judgment), but they make the mechanical parts fast and safe enough to do continuously. Wire the suite into CI so every commit runs it, not just your local loop; a green local run you forgot to push is not a checkpoint.
Best Practices
The habits that separate cleanup from chaos:
- Always refactor with a green test suite. No tests, no refactoring: write characterization tests first on legacy code.
- One technique per step, one commit per step. Small diffs review fast and revert cleanly.
- Name the smell before picking the technique. “Long method” → extract, “type-switch” → polymorphism, “arrow code” → guard clauses.
- Refactor in the path of work. Clean the code your current task touches; do not launch a separate renovation.
- Keep the diff readable. A reviewer who can’t follow your change can’t approve it, and cannot spot the regression either.
- Merge early and often. Long refactoring branches merge worse than the code they were meant to fix.
Common Mistakes
- Refactoring without tests. The single biggest one: it turns a controlled process into a coin flip. Characterization tests first, always.
- Mixing refactoring with behavior changes. “While I’m in here I’ll fix the bug too” breaks the safety contract: if the tests fail, you no longer know whether the refactor or the fix caused it. Separate commits, separate PRs.
- Big-bang rewrites. Three weeks on a branch, one giant merge, six regressions. The alternative is always the same: smaller steps, earlier merges.
- Renaming by find-and-replace. It misses comments, strings, and dynamic references, or worse, catches them when it shouldn’t. Use the IDE’s rename refactoring.
- Extracting too aggressively. A method that needs every local variable passed to it is not a method; it is a symptom of a bigger design problem. If the signature has six parameters, step back and consider Extract Class instead.
- Stopping mid-refactor. Half-moved code is worse than unmoved code: finish the step or revert it; a dangling state confuses everyone after you.
See Also
- Refactoring.com — Martin Fowler’s refactoring catalog with mechanics for every technique here.
- Refactoring.Guru — illustrated refactoring techniques and code smells.
- Working Effectively with Legacy Code — Michael Feathers’ seam-based approach to untested code.
- Guides: complete-guide-clean-code-principles — the style refactoring produces.
- Guides: complete-guide-technical-debt-management — when debt is worth paying down.
- Guides: code-review-best-practices-guide — where refactoring smells get caught.
- Guides: test-driven-development-guide — the test net that makes refactoring safe.
- Companion resources — runnable before/after JavaScript examples with an equivalence smoke test.
Frequently Asked Questions
When should I refactor?
Refactor when the cost of not doing it exceeds the cost of doing it: when a method keeps resisting changes, when the same smell shows up in every PR, or when you are already in the code for a bug fix or feature and the area is hard to work in. Don't refactor for tidiness' sake; refactor because the structure is slowing down the work that matters.
How do I refactor safely?
Get tests in place first (characterization tests that pin down current behavior if the code is legacy), then move in small, single-technique steps, run the tests after each one, and commit after every green run. The workflow is the safety; the technique is secondary.
What is the most common refactoring?
Extract Method, by a wide margin: it's the first response to the "long method" smell, which is the most common smell in real codebases. Rename runs a close second and delivers more comprehension improvement per minute than almost anything else.
When should I replace conditional with polymorphism?
When the same type-check appears in multiple places or the number of cases keeps growing, then each new type touches every switch, and objects pay for themselves. For a single two-branch if, the indirection costs more than the conditional.
What is a guard clause?
An early return or throw at the start of a method that handles a precondition or edge case, so the main logic runs at the top indentation level instead of nested. It turns "check prerequisites, then work" into code you can read top to bottom.
Is refactoring the same as rewriting?
No. Refactoring preserves observable behavior and proceeds in small tested steps; rewriting throws the code away and starts over, which is higher risk, longer, and almost never worth it unless the structure is truly unsalvageable. If a rewrite looks tempting, that's usually a sign the refactoring path was skipped too long, not that the code is hopeless.
How much refactoring is too much?
When the abstraction costs more than the smell it removes: a six-parameter extracted method, a class split that forces callers through three levels of indirection, a "cleanup" that took a week and touched forty files. Good refactoring makes the next change easier; if your change got harder to make, you went the wrong way.
Related Resources
Clean Code Principles: Naming, Functions, Classes
A practical guide to clean code principles: meaningful names, small functions, single responsibility, useful comments, error handling, DRY, and formatting.
GuideTechnical Debt: Track, Prioritize, Pay Down
A working system for technical debt: debt register, impact-vs-effort prioritization, paydown strategies, metrics, and stakeholder reporting.
GuideCode Review Best Practices: Risk-Based Review System
A team operating guide for code review: match scrutiny to blast radius, learn from real public PR threads, handle hard conversations, and measure whether the process works.
GuideTest-Driven Development (TDD) — A Practical Workflow
Learn TDD step by step: write a failing test, make it pass, refactor. Red-Green-Refactor with real examples in Python, JavaScript, and Java.
GuideSoftware Testing Strategy Guide
A practical guide to building a layered testing strategy with unit, integration, contract, and end-to-end tests that your team will actually maintain.