Nguyen Le Phong

Refactoring Toward a Clearer Core, One Small Step at a Time

Trace one business rule, pin its behavior with characterization tests, give it one home and one name, and ship small refactors that make the next change easy.

The ticket says: "Orders with more than five items need manager approval. Change it to ten." Sounds like a one-line change. Then you start digging. The number lives in the order controller, a formatter that builds the warning message, a shared helper called orderUtils, the nightly export job and a test fixture nobody remembers writing. You can still ship the change. It just feels like pulling one cable out from behind a desk where every cable is tangled with every other one.

A before-and-after diagram: on the left, dependencies tangled in every direction; on the right, a clear core in the middle with adapters around the outside.
A good refactor changes which way dependencies point, so the core rules sit in one place and the edges depend on them.

A messy core rarely shows up as an architecture problem. It shows up as daily friction. A feature takes three extra days because the rule exists in three places. A bug fix makes everyone nervous because nobody knows which side effect will wake up. A new teammate asks a simple question and gets a guided tour of old deadlines and special cases.

This post is about fixing that in small, safe steps while you keep shipping features. The aim is modest: make the important rules easy to find, easy to name and hard to bypass by accident.

What counts as refactoring

Martin Fowler's definition is worth keeping close: a refactoring is a change to the internal structure of software that makes it easier to understand and cheaper to modify, without changing its observable behavior (Definition of Refactoring). That last part does a lot of work. If the behavior changes, it's a feature or a fix, and it deserves its own commit and its own review.

It also tells you what a refactor shouldn't be: a rewrite in disguise. Joel Spolsky called rewriting from scratch "the single worst strategic mistake that any software company can make", and his main argument still holds. The ugly old code has been used and tested, and many of its odd-looking lines are bug fixes (Things You Should Never Do). When a whole system really needs replacing, Fowler's Strangler Fig approach moves behavior over piece by piece instead of all at once. For the core of a codebase you work in every day, small refactors are usually enough.

Trace the rule before you move anything

Start by looking, not moving. Pick one business rule and follow it end to end: where it enters the system, where it changes shape, where it's stored, and where the user finally sees the result. Write the trail down as a short list of files and functions.

That list turns "this area feels messy" into something the team can discuss. Without it, refactoring turns into an argument about taste. With it, you can point at specific coupling and decide what's worth protecting. Tracing also finds bugs. Here's what the approval rule from the opening might look like once you line the copies up:

// orders/controller.js
export function submitOrder(order, user, res) {
  if (order.items.length > 5 && user.role !== "manager") {
    return res.status(403).json({ error: "Needs manager approval" })
  }
  // ...
}

// reports/exportOrders.js
const flagged = orders.filter((o) => o.items.length >= 5)  // same rule, different edge

One copy says more than five, the other says five or more. An order with exactly five items goes through checkout without approval but gets flagged in the report. Nobody did this on purpose. Two people copied a rule a year apart. Ask the product owner which one is right before you touch either copy.

Pin the current behavior with tests

Before you change the shape of the code, write tests that describe what it does today, including the odd parts. Michael Feathers calls these characterization tests: they document the system's actual behavior, as "descriptions of what we have rather than statements of correctness" (Characterization Testing). The trick is simple. Write the test with a placeholder expectation, run it, and paste in what the code actually returns. Wrap the current checkout check in a small needsManagerApproval function first, a safe one-line extract, so you have something to test.

// Pins today's behavior, including the edge case the two copies disagree on
test("checkout: exactly five items does not need approval", () => {
  expect(needsManagerApproval(orderWithItems(5))).toBe(false)
})

test("checkout: six items need approval", () => {
  expect(needsManagerApproval(orderWithItems(6))).toBe(true)
})

Once these pass, you can move code around and know right away if you broke something. If product decides the report was right all along, change the test first, in its own commit, so the behavior change is visible in review.

Give the rule one home and one name

Now move the rule into the core, named the way people talk about it in planning. Eric Evans calls this shared vocabulary between developers and domain experts the ubiquitous language (Fowler's summary). If the product team says "manager approval", the code should say needsManagerApproval. A name like checkOrderFlag2 tells the next reader nothing.

// core/approval.js: the rule, in the team's words, with no HTTP or report code
export const APPROVAL_ITEM_LIMIT = 5

export function needsManagerApproval(order) {
  return order.items.length > APPROVAL_ITEM_LIMIT
}

The controller and the export job now call this function instead of keeping their own copies. The next time the limit changes, it really is a one-line change. Look at which way the dependency points, too. The edges (HTTP handlers, report jobs, database code) depend on the core. The core doesn't know they exist. That's the idea behind Alistair Cockburn's hexagonal architecture, whose stated goal is to let an application be driven equally by users, programs, automated tests or batch scripts (Hexagonal Architecture). You don't have to adopt the full pattern to get the benefit. Dependency Direction in Plain Language explains the principle, and Hexagonal Architecture in Practice shows the full version.

What belongs in the core

Business rules and the words for them: limits, states, calculations, what's allowed and what isn't. What stays at the edges: request parsing, response formats, database queries, calls to other services, screen-specific formatting. If a function needs req, res or a database client to answer a business question, part of it is probably in the wrong place.

Small moves, one at a time

Big refactors stall. Small ones ship. A few moves that are almost always safe:

  • Rename a concept so the code matches the words used in planning.
  • Move one rule behind one function, and point the callers at it.
  • Add a characterization test before reshaping anything around it.
  • Split or delete a "shared" helper that actually carries one feature's assumptions into many places. orderUtils with forty unrelated functions is a classic.
  • Keep each move in its own commit, so a reviewer can see that behavior stayed the same.

Timing matters as much as size. Kent Beck's advice, which Fowler quotes when describing preparatory refactoring, fits here: "make the change easy, then make the easy change" (An example of preparatory refactoring). When the approval ticket arrives, spend the first hour pulling the rule into one place, then make the actual change. The ticket pays for the cleanup, and the cleanup lands exactly where someone needed it.

Fowler goes further and argues that a team using refactoring well "should hardly ever need to plan refactoring", because people clean up as they go and leave code better than they found it (Opportunistic Refactoring). A dedicated "refactoring sprint" is often a sign that this habit went missing for a while.

Clarity costs time before it saves time

A team under deadline pressure is right to ask why a small feature needs extra care. Not every file deserves it. Code nobody changes, code that's about to be deleted, or a hotfix during an incident can all wait.

Some areas, though, act like a toll booth. Every feature that passes through pays again in time spent tracing and in fear of breaking something. Those are the places to refactor first. A simple way to find them: look at which files show up in the most commits and the most bug fixes over the last few months. Your version control already has that data.

Be kind to the code's past

Tangled code makes it tempting to judge whoever wrote it. Most tangled cores were built by people shipping under deadlines with half the information you have now. The point of refactoring isn't to prove the past was careless. It's to make the next change depend less on memory, luck and the one person who still knows the hidden path.

That shows up in how you talk about it. "This rule lives in three places, so let's give it one home" lands better in a PR description than "this code is a mess", and it's more accurate. If you're digging into a much older system, Dealing with Legacy Code covers that wider situation.

Try this week

  • Pick the rule your team changes most often and trace it end to end. Write down every file it touches.
  • If the copies disagree, ask product which one is right before changing either.
  • Write two or three characterization tests that pin today's behavior.
  • Move the rule into one function named the way the team talks about it, and point the callers at it.
  • Ship it as its own small PR, separate from any behavior change.

A clearer core won't make a codebase effortless. It makes the important parts easier to find. When a new teammate can open the project and see where the central rules live, they inherit more than tidier files. They can make their first change without asking around for directions.

What did you think?

Frequently asked questions

What is refactoring, exactly?
Martin Fowler defines it as a change to the internal structure of software that makes it easier to understand and cheaper to modify without changing its observable behavior. If the behavior changes, it's a feature or a fix, and it should go in its own commit and review.
Should I rewrite a messy core from scratch?
Usually not. Old code has been used and tested, and many of its odd-looking lines are bug fixes. Small refactors in the area you're already changing are safer. When a whole system needs replacing, move behavior over piece by piece, as in Fowler's Strangler Fig approach.
What is a characterization test?
A test that records what the code does today rather than what it should do. Michael Feathers describes them as documentation of a system's actual behavior. Write the test with a placeholder expectation, run it and paste in the real result, then refactor knowing the test will catch any change.
When is the right time to refactor?
Right before a change in that area, following Kent Beck's advice to make the change easy and then make the easy change. Fowler argues a team that refactors as it goes should rarely need to plan refactoring. Skip code nobody changes, code about to be deleted and hotfixes during incidents.
What belongs in the core of a codebase?
Business rules and the names for them: limits, states, calculations and what's allowed. Request parsing, response formats, database queries and calls to other services belong at the edges, which depend on the core rather than the other way around.