Refactoring for readability
August 28, 2022A simple rename can save hours of time in the future.
I’ve been doing a lot of refactoring lately. This is pretty common when I join a new project, especially one with a lot of technical debt.
At this stage, a large portion of my refactoring is purely readability related.
“Isn’t all refactoring readability-related?” one might ask.
Perhaps in a sense. Code structure is largely about readability.
But what I mean is that a lot of my refactoring is just trivial things, like renaming variables.
While pairing on Friday, we came across a function called
CheckUser. What does that mean? We didn’t know. So we started reading that function for comprehension, when we found that it called another function called
CheckLimited. Uhh. Here we go again.
(Pro tip: Never use the name
Check in your functions)
After reading through that function, we found that it was returning
true if the relevant user had a flag called
AccessLimited enabled, or if the user’s parent account had the same flag. So we renamed that function to
HasAccessLimited. We also added a bit of GoDoc so that future readers of the code would hopefully never face the same confusion we did.
We then did the same exercise for
CheckUser, and found it was only being legitimately used in one place, for a very specific use-case, so we renamed the function to
UserCanCreateCards, and added some more GoDoc.
The refactoring itself, to codify what we had learned, took about five minutes. But reading the code for comprehension took over an hour. Fortunately, that’s an hour nobody should ever have to spend again.
What is refactoring?
As in alegebra, code (re)factoring doesn't change the meaning of an expression, only the representation.
Many people don't understand refactoring, and this leads to several anti-patterns.
Refactoring itself is worthless
Why refactoring doesn't, and shouldn't provide direct business value