What is refactoring and what it is not
refactoring definition, behavior preservation, refactoring vs rewriting, refactoring vs optimization, safe refactoring steps
Refactoring: Improving Structure Without Changing Behavior
Refactoring means improving the internal structure of code without changing its observable behavior. That last part is critical: if behavior changes, it's not refactoring — it's a bug or a new feature.
This distinction matters because refactoring should be safe. You should be able to refactor freely, at any time, with confidence that nothing breaks. That confidence comes from tests and from making small, verifiable steps.
// Before — works but hard to read
function p(u) {
return u.a >= 18 && u.s === 'active' && !u.b;
}
// After refactoring — same logic, readable
function isEligibleForPromotion(user) {
const isAdult = user.age >= 18;
const isActive = user.status === 'active';
const isNotBanned = !user.isBanned;
return isAdult && isActive && isNotBanned;
}Refactoring is not:
Rewriting — rewriting throws away the existing code and starts fresh. Refactoring keeps behavior and incrementally improves structure.
Optimization — optimization changes how code performs. Refactoring changes how code reads. They're separate activities, done at separate times.
Adding features — never add features during a refactor. It mixes two purposes and makes it impossible to isolate what caused a regression.
The refactoring workflow: write or verify tests first, make one small change, run tests, repeat. Each cycle should take minutes, not hours. If a refactor takes more than a day, it's probably a rewrite.
Don't refactor code you don't understand. Read it, write a test that describes what it does, then refactor. The test is your safety net.
