To put it simply, refactoring is tidying up code so it is easier to read and change, without changing what the code actually does. The program behaves exactly the same before and after. Same inputs, same outputs, same bugs, if I am being honest. The only thing that changes is the shape of the code itself.
The first mistake I made with refactoring was treating it like rewriting. I opened a messy function, decided the whole thing was garbage, and started over from a blank file. Two hours later I had a prettier function that failed three tests the old one passed. That is not refactoring. That is rewriting, and rewriting is a gamble. Refactoring is the careful version: small steps, each one safe, with the tests still green after every step.
The kitchen analogy, because it fits too well
A kitchen is the best way I have found to explain it. Imagine you cook in a kitchen where the knives are in a drawer across the room, the spices are mixed in with the cleaning bottles, and the pan you use every day is buried under a stack of baking trays you never touch. You can still cook dinner in that kitchen. The food comes out fine. But every meal takes longer than it should, and every time you reach for something you have to think about where it is.
Refactoring is reorganising that kitchen while the menu stays the same. Knives next to the chopping board. Spices together on one shelf. The everyday pan at the front. Nothing about the food changes. Dinner just gets easier to make, and the next person who walks into the kitchen can find things without asking you. Code works the same way. A function that does five jobs at once can still work perfectly. It is just painful to change, and the pain grows every time someone touches it.
What a refactor actually looks like
Here is the smallest version of a real refactor. Say you have a function that works out a shop total, and it has grown a few extra jobs over time:
def total(items, member):
s = 0
for i in items:
s += i["price"] * i["qty"]
if member:
s = s * 0.9
if s > 100:
s -= 10
return round(s, 2)
That function works. It also hides three separate ideas in one place: adding up the items, the member discount, and the big-order discount. Nobody reading it can tell at a glance which part does what, and if the discount rules change, you have to edit this one pile carefully. A refactor pulls the ideas apart and gives each one a name:
def subtotal(items):
return sum(item["price"] * item["qty"] for item in items)
def apply_discounts(amount, member):
if member:
amount *= 0.9
if amount > 100:
amount -= 10
return amount
def total(items, member):
return round(apply_discounts(subtotal(items), member), 2)
Same result for every order. The difference is that now each piece says what it does, and when the shop changes its discount rules, you know exactly where to go. That is the whole trick. Nothing clever. Just names and small pieces.
One small change at a time, with the tests run before and after. If a step goes red, you undo just that step.
The rule that keeps it safe
The one rule that matters is this: never change behaviour and structure at the same time. If you are adding a feature, add the feature. If you are cleaning up, clean up. Doing both in one edit is how you end up staring at a failing test at midnight, unable to tell whether the bug came from your new feature or your tidy-up.
The way professionals keep it safe is embarrassingly simple. They run the tests before they start, so they know the starting point is green. Then they make one small change — rename a variable, pull a block of code into its own function, delete a duplicated line — and run the tests again. Still green, move on. Red, undo that one step. It sounds slow, and the first time you do it, it feels slow. But it is far faster than the alternative, which is spending an afternoon hunting a bug you created yourself while trying to be tidy.
There is a name for the discipline of doing it in tiny steps, and it comes from Martin Fowler's book Refactoring, first published in 1999 and updated in a second edition in 2018. Fowler's point, the one that stuck with me, is that refactoring is not a big event you schedule once a year. It is a habit you fold into ordinary work. You are fixing a bug in a function, you notice the variable names lie about what the values are, you rename them while you are there. Ten seconds now, ten minutes saved for the next person.
When to refactor, and when to leave it alone
Not all messy code deserves a refactor. Code that works and nobody ever touches again can stay messy. I have a small script that renames files for me, written in a hurry two years ago, and it looks like a crime scene. I have never refactored it, because I run it, it works, and I never need to change it. Refactoring code nobody reads is polishing a door nobody opens.
The code that earns a refactor is the code you keep coming back to. The signs are easy to spot once you know them. A function so long you have to scroll to see the end of it. The same block of code copied in three places, with a small difference in each copy that nobody can explain. A variable called data or temp that holds something very specific. A comment that says "do not touch this, it works somehow". Every one of those is the code telling you it has become hard to think about, and hard-to-think-about code is where the next bug will live.
There is also a limit worth knowing. Refactoring cannot fix a bad design. If the whole structure of a program is wrong — if it was built for one user and now serves ten thousand — no amount of renaming will save it. That is a rewrite, and rewrites need their own plan, their own tests, and a very honest conversation about the risk. Refactoring is for code whose shape is right and whose details have gone stale.
The habit that pays for itself
I keep a small rule for myself now. Every time I open a file to fix something, I leave one thing cleaner than I found it. Rename one lying variable. Split one function that does two jobs. Delete one duplicated block. Never a big cleanup, never in the same edit as the fix. It takes minutes, and after a few months the files I touch most have quietly become pleasant to work in. That is the real payoff of refactoring. Not a dramatic before-and-after, just a codebase that stops fighting you.
- Refactoring changes the shape of code, never what it does — same inputs, same outputs.
- Small steps with the tests green after each one is what makes it safe; rewriting from scratch is a different, riskier thing.
- Refactor the code you keep returning to, and leave working code nobody touches alone.
- Never mix a behaviour change and a cleanup in one edit — that is where the midnight bugs come from.
Rewriting starts over and risks the behaviour. Refactoring keeps the behaviour and changes only the shape.
References and further reading
- Code refactoring — Wikipedia
- Refactoring — Martin Fowler's catalog
- Refactoring — Refactoring Guru
- Refactoring: Improving the Design of Existing Code — Martin Fowler
— Min SiThu Software Engineer & Tech Content Creator https://minsithu.org
About the author
- Nubbad Developer. | Now I accidentally create problems.
Comments
Join the discussionNo comments yet. Be the first to comment.

