August 26, 2021 • 2 min read
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.
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.
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.
Here are some changes that probably make the code easier to read, but aren’t defensible by themselves:
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.
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. Also, tests are fair game; refactor away.
Blog of Jake Worth, software engineer in Maine.