Great engineers refactor constantly, even if they have to slip it into their normal workflow.

“Always be closing.”

The hard-nosed sales mantra from Glengarry Glen Ross became shorthand for relentless improvement. In the same spirit (but with much less swearing), a good engineer should always be refactoring. Here’s why.

To Clean or Not to Clean

It’s generally agreed that clean code is easier to understand, cheaper to maintain, and much more extensible. At its core, refactoring is cleaning up existing code without altering its perceived functionality.

A common objection to refactoring is that there isn’t time to actually do it. Teams see it as a luxury. The relentless drive for new features simply doesn’t allow for refactoring, especially because refactoring changes nothing from an external point of view. That can be a hard sell to your product owner.

But clean code makes your life easier. Clean code pays for itself and slows the accumulation of technical debt.

So sneak it in.

That’s right. I’m suggesting a slight bit of subterfuge. A little misdirection even. Why not clean up a few things in every pull request?

Be Vigilant

A good engineer has a vision of where the codebase should be heading. It might take a while to get there, but you know the messy parts, the backlog, the roadmap, the technical debt, the security holes, and the documentation gaps.

As you go about your regular feature development, be on the lookout for refactorings that can advance your larger agenda. Like one of those hyper-observant TV show detectives surveying a crime scene, pay close attention to all the code you stumble across.

When you notice a code smell or something slightly off near your current focus, alarm bells should go off: “Don’t let this opportunity pass!” Take a few minutes and fix it now, before inspiration fades.

Don’t say it’s not your problem. Don’t pretend you can unsee it. Just roll up your sleeves and get it done.

A Simple Example

Refactoring doesn’t necessarily mean changing thousands of lines of code. It can be just a small chunk of code here and there. These little micro-refactorings add up over time. In fact, the more you get into the habit of constant cleanup, the less you will need to do major refactorings in the future.

To illustrate micro-refactoring, let’s look at an “extract method” Golang example.

Let’s say you are tackling a feature that requires knowing how many days it has been since a user last logged in. You notice an existing method that determines if a user is dormant by using that same information:

func IsDormant(user User, asOf time.Time) bool {
  days := int(asOf.Sub(user.LastLogin).Hours() / 24)
  return days >= 8
}

You want to re-use the last login calculation instead of copying and pasting it, so you take the internal variable, days, and extracting it into a separate method, DaysSinceLastLogin:

func IsDormant(user User, asOf time.Time) bool {
  return DaysSinceLastLogin(user, asOf) >= 8
}

func DaysSinceLastLogin(user User, asOf time.Time) int {
  return int(asOf.Sub(user.LastLogin).Hours() / 24)
}

This allows the last login logic to be tested and reused. If you write a unit test, you’ll spot an edge case that should be handled (a potential panic if a user has never logged in).

It also makes future enhancements easier. For example, it might make sense to make IsDormant and DaysSinceLastLogin methods on the User struct instead of being standalone. Likewise, consider replacing the hard-coded value 8 with something more descriptive like DormantDaysThreshold.

This is a simple example, just a few lines of code. But that’s the beauty. It shows a small refactoring can add value by revealing a potential bug and pointing towards future improvements.

To learn more about the craft of refactoring and see all the small ways to improve your code, check out online resources such as the refactoring catalog from Martin Fowler’s book or the Refactoring Guru.

A Refactoring Mindset

Having a vision for your codebase is easy. Knowing how to get it there is harder. Spotting refactoring opportunities takes practice. One way to get started is to consider which categories of refactoring are necessary to transform your code.

Here are some common refactoring themes to think about:

🧹 Remove Duplication — Collapse copy and pasted logic into a single function.

🧰 Extract Shared Utility or Library — Move common logic out of per-service implementations. Normalize integrations (e.g., all services use the same auth client).

🧱 Add Common Infrastructure — Introduce observability (logging, tracing, metrics). Centralize error handling or retries.

⚙️ Make Code More Testable — Break apart tightly coupled logic. Extract interfaces so dependencies can be mocked or stubbed.

🔄 Prepare for a Feature Change — Flatten complex conditionals or nested logic. Reorganize files or classes to fit new responsibilities.

🏗️ Support a New Architecture — Break apart a monolith. Introduce event-driven patterns, dependency injection, or async processing.

🚦 Reduce Cognitive Load — Split giant files or classes into logical, focused units.

🔐 Improve Security or Compliance — Centralize access control logic. Refactor insecure patterns (e.g., manual SQL concatenation → parameterized queries).

🚀 Improve Performance — Replace naive algorithms with optimized ones. Reduce memory churn or unnecessary computation in hot paths.

👥 Ease Onboarding or Handoff — Refactor code that only “Pat” understands into something team-readable. Introduce docs/comments/test coverage as part of structural cleanup.

The 20%

Some might object that surely not all refactorings can be snuck in. I’ll grant you that. Let’s apply the 80–20 rule and stipulate that 20% of refactorings need to be done on the up-and-up.

These should be an easier sell, however, because when you get to the point where you need a full, honest-to-goodness refactor, it is most definitely going to be in service of some larger goal.

For example, before working on a performance improvement ticket, you first need to add tracing and metrics so you can develop a finer picture of current performance and identify hotspots.

Refactoring Starts with Testing

It is probably self-evident, but I must point out that refactoring is much easier (and less nerve-racking) if your codebase has an accompanying suite of tests that pass before and after the refactoring. Having tests is also valuable for a bunch of other reasons. If your project doesn’t have strong testing, then add some tests first to unlock future refactorings.

Code Review Considerations

My advice in this article runs counter to the standard guideline to not mix refactoring work and regular feature development. The objection is that it makes it harder for the team to do code reviews if unrelated changes are included. That’s a fair point. When refactoring during feature work, keep it small and (ideally) related to the main thrust of the change.

A good rule of thumb for any pull request is to limit it to 500 lines of code changes. A second rule of thumb is that ancillary refactoring changes should be no more than 20% of the PR.

When you do have dedicated refactoring PRs, keep it focused and around this size. Sometimes a PR has to be greater than 500 lines of code, especially when working on a repo-wide refactor. In those cases, coordinate well with your colleagues to prepare them for the change and to minimize merge conflicts.

Make Every Commit Count

Every time you touch the codebase, you have a choice: leave it a little better, or leave it a little worse.

Refactoring doesn’t have to be a grand event. Small improvements (extracting methods, renaming confusing variables, breaking apart long methods, etc.) add up over time. They prevent technical debt from piling up and make future changes easier and safer.

If you see something, fix something.

Always be refactoring!