August 26, 2021 • 2 min read
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. —Martin Fowler
“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 often request that changes be removed. Even objective improvements that support my personal preferences.
Refactors are not free. In this post, I’ll list a few times when I think a refactor is worse than leaving the code unchanged.
A mentor once told me: “refactoring without tests is not a thing.” In other words, refactoring without tests is not refactoring.
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, very soon you’re going to break something.
Refactoring without tests is always a risk.
You may find yourself reading a file, start refactoring it, and then realize you don’t need to change it. Should you commit the refactor anyway? Probably not.
When I read a commit message that says “Fixes profile page crashing”, I assume an atomic commit, where everything in that commit is supports that goal. Only by closely reading the diff could I learn that isn’t true. It’s just easier to assume that everything matters.
Here are some changes that probably make the code easier to read, but aren’t defensible by themselves:
Why? For one, you’re stepping on the Git history. Many developers use Git to understand past decisions. Touch a line of code, and you bury that context under a new commit. For most developers I’ve met, that puts the context out of reach. Don’t do it casually.
So what are good refactors? If all of these are true, you’re on the right track:
If you meet all these criteria, go ahead and commit your refactor. One exception to this are test; refactor them as much as you want.
Blog of Jake Worth, software engineer in Maine.