Jake Worth

When Should I Not Refactor?

August 26, 20212 min read

  • refactoring

Martin Fowler defines refactoring as:

Refactoring (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.

“Easier to understand and cheaper to modify”: those sound pretty good! Should we be refactoring all of the time? Besides time, what are the costs of refactoring?

When I review code, I request that some refactors, even objective improvements, be removed from a pull request. Refactors are not free. In this post, I’ll list a few times when I think a refactor is worse than leaving the code as-is.

No Tests

A mentor once told me: “refactoring without tests is not a thing.” Do you have tests? Can you run them? Do you trust them?

A type system, or a pre-compiled language, will catch some of the mistakes you’ll make while coding. But in a dynamic language like Ruby, with no tests? You’re going to break something.

Refactoring without tests is always a risk.

It’s the Only Change

You may find yourself reading a file, start refactoring it, and then realize you don’t need to change anything in the file. Should you commit the refactor anyway? Probably not.

When I read a commit message that says “Fixes profile page crashing”, I can’t help but assume everything in that commit is relevant to that goal. If it isn’t, I have to read through the diff and earn that knowledge myself. It’s easier to code like everything matters and assume that of your teammates’ code.

It’s Arbitrary

Here are some changes that probably make the code easier to read, but aren’t defensible by themselves:

  • ❌ Adding or removing whitespace
  • ❌ Breaking up long lines
  • ❌ Renaming variables in trivial ways (_e to _event)
  • ❌ Personal style preferences that are not enforced with tooling or conventional to the language

Many developers use Git to understand past decisions. Touch a line of code, and you bury that context under your new commit. For most developers I’ve met, that puts the context out of reach. Don’t do it lightly.

Good Refactors

So what are good refactors? If all of these are true, you’re on the right track:

  • ✅ The file needs to be changed to improve the user or developer experience
  • ✅ There’s test coverage, type safety, it’s a compiled language, or the change is so simple that you can’t mess it up. Although you still can
  • ✅ The refactor improves the code. Can be subjective, but there are good and bad examples

If you meet all these criteria, go ahead and commit your refactor. Also, tests are fair game; refactor away.

Blog of Jake Worth, software engineer in Maine.

© 2021 Jake Worth.