Refactoring Basics: Improving Code Without Breaking It
Refactoring changes code structure without changing behaviour. Learn the core techniques, how to stay safe, and when to refactor.
By Velloreth
What refactoring is
Refactoring is changing the structure of code without changing its observable behaviour. The program does the same thing before and after; only the internal organisation differs.
The definition has two halves, and both matter.
Structure changes. You rename things, extract functions, move code between modules, replace conditionals with polymorphism.
Behaviour does not change. The same inputs produce the same outputs, the same side effects occur, the same errors are thrown.
The second half is what makes refactoring safe. Because behaviour is preserved, you can refactor code you do not fully understand, as long as you can verify the behaviour is unchanged.
Tests are the safety net
Without a way to verify behaviour, refactoring is just editing and hoping.
// Before refactoring
function calc(items: Item[]): number {
let t = 0;
for (const i of items) {
if (i.active) t += i.price * i.qty;
}
return t;
}
// After refactoring — same behaviour, clearer
function calculateTotal(items: Item[]): number {
return items
.filter((item) => item.active)
.reduce((total, item) => total + item.price * item.qty, 0);
}
The test that verifies this is simple:
test('calculates total of active items', () => {
const items = [
{ active: true, price: 10, qty: 2 },
{ active: false, price: 100, qty: 1 },
{ active: true, price: 5, qty: 3 },
];
expect(calculateTotal(items)).toBe(35);
});
Run it before and after. If it passes both times, the refactoring preserved behaviour for that case.
The test does not prove equivalence for all inputs, which is why you want several cases, including edge cases: empty array, all inactive, zero quantity.
Work in small steps
The discipline that makes refactoring safe is small steps with tests between them.
Bad: rewrite a 200-line function in one edit, then run the tests.
Good: extract one helper, run tests. Rename a variable, run tests. Replace one conditional, run tests.
The reason is diagnostic. If you make twenty changes and the tests fail, you must find which change broke it. If you make one change and the tests fail, you know exactly what to look at.
Modern tooling makes this cheap. An IDE’s rename refactoring is instant and safe. Extract-function is a keystroke. Use the automated refactorings where they exist, because they are verified by the tool.
The core refactorings
Extract function
The most valuable refactoring. Take a block of code and give it a name.
// Before
function printInvoice(order: Order) {
console.log('INVOICE');
console.log(`Customer: ${order.customer.name}`);
console.log(`Date: ${order.createdAt.toISOString()}`);
let total = 0;
for (const item of order.items) {
total += item.price * item.qty;
}
console.log(`Total: ${total}`);
}
// After
function printInvoice(order: Order) {
console.log('INVOICE');
printHeader(order);
console.log(`Total: ${calculateTotal(order.items)}`);
}
function printHeader(order: Order) {
console.log(`Customer: ${order.customer.name}`);
console.log(`Date: ${order.createdAt.toISOString()}`);
}
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
The extracted functions have names that explain what the code does, and each can be tested independently.
Rename
Names are the primary way code communicates. A bad name costs every reader.
// Before
const d = new Date();
const x = users.filter((u) => u.a);
// After
const now = new Date();
const activeUsers = users.filter((user) => user.isActive);
Renaming is mechanical and safe with tooling. Do it whenever a name does not convey intent.
Remove duplication
When the same logic appears three times, extract it.
// Before
const activeUsers = users.filter((u) => u.status === 'active');
const activePosts = posts.filter((p) => p.status === 'active');
const activeComments = comments.filter((c) => c.status === 'active');
// After
const isActive = <T extends { status: string }>(item: T) => item.status === 'active';
const activeUsers = users.filter(isActive);
const activePosts = posts.filter(isActive);
const activeComments = comments.filter(isActive);
The rule of three applies: two occurrences might be coincidence, three suggests a real pattern.
Simplify conditionals
Complex conditionals are hard to read and hard to test.
// Before
if (user.age >= 18 && user.country === 'US' && !user.banned && user.verified) {
// ...
}
// After
const canPurchase = user.age >= 18
&& user.country === 'US'
&& !user.banned
&& user.verified;
if (canPurchase) {
// ...
}
Extracting the condition into a named variable documents what it means. For more complex cases, extract a predicate function.
Replace magic numbers
// Before
if (retries > 3) { /* ... */ }
setTimeout(fn, 86400000);
// After
const MAX_RETRIES = 3;
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
if (retries > MAX_RETRIES) { /* ... */ }
setTimeout(fn, ONE_DAY_MS);
A named constant explains what the number means and gives it one place to change.
Introduce a parameter object
// Before
function createUser(name: string, email: string, age: number, country: string, plan: string) { }
// After
interface CreateUserInput {
name: string;
email: string;
age: number;
country: string;
plan: string;
}
function createUser(input: CreateUserInput) { }
Long parameter lists are hard to call correctly. A parameter object names each field and makes the call site readable.
When to refactor
Before adding a feature. If the current structure makes the change hard, refactor first, then add the feature. This is the most valuable time to refactor, because you are about to touch the code anyway.
When you see duplication for the third time. The pattern is now clear enough to abstract.
When you cannot understand the code. If you have to read a function three times to follow it, it needs work.
When a bug reveals a design problem. Fix the design, not just the symptom.
When tests are hard to write. Difficulty testing usually indicates tight coupling, which refactoring can fix.
When not to refactor
When you do not have tests and cannot add them. Refactoring without a safety net is risky. Add characterisation tests first.
When you are under time pressure and the code works. Refactoring is an investment; sometimes shipping is the priority.
When the code is about to be deleted. Do not polish code that is going away.
When you do not understand the code. Refactoring code you do not understand is how bugs get introduced. Understand first, then change.
As a separate project. Large refactoring phases are risky, hard to review, and rarely finish. Refactor continuously in small amounts.
Refactoring legacy code
The hard case is code with no tests. The approach, from Michael Feathers:
- Find a seam — a place where you can substitute behaviour for testing.
- Write characterisation tests — tests that record what the code currently does, even if that behaviour is wrong.
- Refactor with the safety net in place.
- Fix the behaviour separately, once the structure is clear.
Characterisation tests are unusual because they assert the current behaviour rather than the desired behaviour. Their purpose is to detect change, not to verify correctness. Once you have them, you can refactor safely, and then fix the bugs deliberately.
Practical guidance
- Refactor in small steps, running tests after each.
- Use automated refactorings where the IDE provides them.
- Extract functions whenever a block needs a comment to explain it.
- Rename aggressively — names are the cheapest documentation.
- Refactor before adding a feature, not after.
- Do not refactor without a safety net.
- Keep refactoring commits separate from behaviour changes, so reviews are clear.
- Refactor continuously rather than in large phases.
For the related practices, see writing clean functions and code review checklist. For the principles behind the decisions, DRY, KISS and YAGNI and technical debt conversation.
Quotable summary
Refactoring changes the structure of code without changing its observable behaviour, which is what makes it safe to apply to code you do not fully understand. Tests are the safety net; without them, refactoring is editing and hoping. Work in small steps with tests between them, so a failure points at one change rather than twenty. The most valuable refactorings are extracting functions, renaming, removing duplication, and simplifying conditionals, and the rule of three governs when duplication is worth extracting. Refactor before adding a feature, when you see duplication for the third time, or when you cannot understand code you need to change — and refactor continuously in small amounts rather than in large dedicated phases.