Notes Tutorials

Refactoring: clear over clever

Refactoring means improving the structure of code without changing what it does. Why tests come first, how to work in small safe steps, one messy function cleaned up from start to finish, why the shortest version isn't the best one, and when to leave code alone.

7 min readAlso available in Bahasa Indonesia →

Code that works isn’t finished. It still has to be read, changed, and debugged, usually by someone who wasn’t there when it was written. Refactoring is how you keep it in a state where that’s possible.

Martin Fowler, who wrote the standard book on the topic, defines it precisely. As a noun: “a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.” As a verb: “to restructure software by applying a series of refactorings without changing its observable behavior.”

The key phrase appears twice: without changing its observable behavior. Refactoring is not fixing bugs, and it’s not adding features. The program does exactly the same thing afterwards. Only the code is different.

Tests first, always

How do you know behavior didn’t change? You don’t, unless you check. So refactoring starts with tests: the characterization tests from part 12 if the code has none, or the unit tests from part 14 if it does.

Fowler’s site describes the method: “Its heart is a series of small behavior preserving transformations.” Each step is small: rename one thing, extract one function, remove one duplication. After each step you run the tests. If they pass, commit (part 16) and take the next step. If they fail, the problem is in the few lines you just changed, so it’s easy to find or undo.

Big rewrites skip all of this, which is why they so often break things nobody noticed until much later.

A messy function

Here’s a function that calculates an order summary. It works, and it’s the kind of code that ends up in every real project:

def proc(o):
    t = 0
    for i in o["items"]:
        if i["qty"] > 0:
            if i["qty"] >= 10:
                t += i["price"] * i["qty"] * 95 // 100
            else:
                t += i["price"] * i["qty"]
    if o["member"]:
        if t > 500000:
            s = 0
        else:
            s = 15000
    else:
        if t > 1000000:
            s = 0
        else:
            s = 25000
    return {"subtotal": t, "shipping": s, "total": t + s}

Some code smells, in the sense of “any characteristic of source code that hints at a deeper problem”: names that say nothing (proc, o, t, s), magic numbers (part 11), nesting four levels deep, and two separate jobs, line pricing and shipping, mixed in one function. Note that “Code smells are usually not bugs”. This code is correct. It’s just harder to change than it needs to be.

Step 0: pin the behavior. Five cases covering a normal order, a member, free shipping with a bulk discount, a refund row, and an empty order:

CASES = [
    ({"member": False, "items": [{"price": 85000, "qty": 2}]},
     {"subtotal": 170000, "shipping": 25000, "total": 195000}),
    ({"member": True, "items": [{"price": 85000, "qty": 2}]},
     {"subtotal": 170000, "shipping": 15000, "total": 185000}),
    ({"member": True, "items": [{"price": 4000, "qty": 10}, {"price": 500000, "qty": 1}]},
     {"subtotal": 538000, "shipping": 0, "total": 538000}),
    ({"member": False, "items": [{"price": 100, "qty": -1}]},
     {"subtotal": 0, "shipping": 25000, "total": 25000}),
    ({"member": False, "items": []},
     {"subtotal": 0, "shipping": 25000, "total": 25000}),
]

Then a series of small steps, each followed by a test run:

  1. Rename proc to summarize_order, o to order, t to subtotal, s to shipping.
  2. Extract the price of one line into line_total(price, qty). Turn the nested if into an early return for qty <= 0.
  3. Extract shipping into shipping_fee(subtotal, tier).
  4. Replace the magic numbers with named tables, so “member” and “regular” are data, not branches.

The result:

FREE_SHIPPING_ABOVE = {"member": 500_000, "regular": 1_000_000}
SHIPPING_FEE = {"member": 15_000, "regular": 25_000}


def line_total(price, qty):
    if qty <= 0:
        return 0
    total = price * qty
    if qty >= 10:
        total = total * 95 // 100
    return total


def shipping_fee(subtotal, tier):
    if subtotal > FREE_SHIPPING_ABOVE[tier]:
        return 0
    return SHIPPING_FEE[tier]


def summarize_order(order):
    tier = "member" if order["member"] else "regular"
    subtotal = sum(line_total(i["price"], i["qty"]) for i in order["items"])
    shipping = shipping_fee(subtotal, tier)
    return {"subtotal": subtotal, "shipping": shipping, "total": subtotal + shipping}

It’s 24 lines instead of 19. Shorter was never the goal. Each function now does one thing, has a name that says what, and can be tested on its own. The business rules (thresholds and fees) sit at the top where anyone can find them. And the same five cases pass, for the old version and the new one:

15 passed in 0.02s

Make the change easy, then make the easy change

Refactoring pays off when the next change arrives. Say the business adds a “gold” tier with free shipping on everything.

In the original proc, that’s another nested branch inside the shipping if, next to the two that are already there. In the refactored version, it’s two entries in the tables:

FREE_SHIPPING_ABOVE["gold"] = 0
SHIPPING_FEE["gold"] = 0
shipping_fee(170000, "gold")    → 0
shipping_fee(170000, "member")  → 15000
shipping_fee(170000, "regular") → 25000

Kent Beck put this approach in one line, quoted by Fowler: “make the change easy, then make the easy change”. The full version adds a warning: “make the change easy (warning: this may be hard), then make the easy change”. Fowler calls this preparatory refactoring: before adding a feature, reshape the code so the feature fits naturally.

One more rule from the same idea: don’t refactor and change behavior in the same step. Fowler describes it as two hats: “When you’re wearing the refactoring hat, every change you make preserves observable behavior”, and the hat “keeps the tests green”. Refactor with green tests, commit, then switch hats and add the feature. Two commits, each easy to review.

Clever is not the same as good

Here’s a third version. It passes the same five tests:

def proc(o):
    return (lambda t: {"subtotal": t, "shipping": (s := 0 if t > (5e5 if o["member"] else 1e6) else (15000 if o["member"] else 25000)), "total": t + s})(sum(i["price"] * i["qty"] * (95 if i["qty"] >= 10 else 100) // 100 for i in o["items"] if i["qty"] > 0))

Two lines. A lambda, the walrus operator, nested conditional expressions. It’s clever, and it’s the worst of the three. Try adding the gold tier to it. Try finding the free-shipping threshold. Notice also that 5e5 and 1e6 are floats, a type change from the original that happens to work here and might not somewhere else (part 2).

The Zen of Python has three lines for this:

“Simple is better than complex.” “Readability counts.” “If the implementation is hard to explain, it’s a bad idea.”

Clever code optimizes for the moment of writing. Clear code optimizes for every moment after, which is most of them.

The same moves in PHP

Deep nesting is one of the most common smells, in any language. A refund check with every condition nested:

function canRefundNested(array $order, int $daysSincePaid): bool {
    if ($order['status'] === 'paid') {
        if ($daysSincePaid <= 7) {
            if (!$order['digital']) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

The same logic with guard clauses: handle each reason to say no first, and return early.

function canRefund(array $order, int $daysSincePaid): bool {
    if ($order['status'] !== 'paid') {
        return false;
    }
    if ($daysSincePaid > 7) {
        return false;
    }
    return !$order['digital'];
}

Checking both on the same cases:

paid    digital=false days=3   nested=true  guard=true  same
paid    digital=true  days=3   nested=false guard=false same
paid    digital=false days=10  nested=false guard=false same
pending digital=false days=1   nested=false guard=false same

Same behavior. Now each rule is one if you can read on its own, and adding a fourth rule is adding one more.

Common refactorings

You don’t need a catalog to start. These few cover most everyday cleanups:

  • Rename a variable, function, or class so the name says what it is. Editors do this safely across a whole project.
  • Extract function: give a block of code a name. If you feel like writing a comment above a block to explain it, the comment is probably the function name.
  • Inline: the reverse, when a function or variable adds a name but no clarity.
  • Replace magic number with a named constant.
  • Guard clauses instead of deep nesting.
  • Replace conditional with data: a table or map instead of a chain of ifs, as with the shipping tiers.
  • Remove duplication, but not too early. The rule of three: “two instances of similar code do not require refactoring, but when similar code is used three times, it should be extracted into a new procedure.” Two similar pieces might diverge. By the third, you know the pattern.
  • Delete dead code. Git remembers it if you ever need it back.

When not to refactor

  • No tests and no time to write them. Without a safety net, “cleanup” is just risk.
  • Code that’s about to be deleted or rewritten anyway.
  • Code nobody needs to change. Ugly but stable code in a corner nobody touches can stay ugly.
  • In the same commit as a bug fix or feature. Separate hats, separate commits.
  • Just to match your taste. If the team’s style is different from yours but consistent, consistency wins.

The best moment to refactor is usually right before you change something: you’re already reading that code, and you’re about to benefit from making it clearer.

Why this matters day to day

  • Change gets cheaper. Time spent making code clear is paid back every time someone touches it.
  • Fewer bugs hide in clear code. Deep nesting and vague names are where wrong conditions go unnoticed.
  • Reviews are easier. A refactoring commit with green tests and a feature commit are each simple to review; mixed together, neither is.
  • AI tools are good at refactoring, and confident when they’re wrong. Ask for one small refactoring at a time, run the tests after each, and read the diff. The rules don’t change because a tool is doing the typing.

Try it yourself

  1. Copy the original proc and the five test cases. Do the four refactoring steps yourself, running the tests after each one.
  2. Add the gold tier to the original proc and to the refactored version. Compare the diffs.
  3. Find a function with three or more levels of nesting in your own code and rewrite it with guard clauses. Check it with a few cases before and after.
  4. Find something clever you wrote a while ago. Can you still explain it in one sentence? If not, rewrite it plainly.

Summary

  • Refactoring changes structure without changing observable behavior.
  • Tests first, then small steps, running tests and committing after each.
  • Aim for clear, not short: good names, one job per function, named rules, shallow nesting.
  • Make the change easy, then make the easy change: refactor before adding a feature, in a separate commit.
  • Clever code is cheap to write and expensive to read; prefer the plain version.
  • Common moves: rename, extract, inline, named constants, guard clauses, data instead of conditionals, remove duplication after the third time.
  • Know when to leave code alone.

References