When to Refactor Your Code
I recently answered a question on Quora about when to consider refactoring code.
First, I think a shared understanding of refactoring is important.
For me, refactoring is when we change the implementation of a piece of code without changing the behavior. That’s the entire definition - Change the implementation, but not the behavior.
As a result, I will generally not refactor code unless it has a solid set of tests around it. If I see code that needs refactoring, but has insufficient tests, I will add character tests.
When I am refactoring, it is done in relatively small steps. This allows me to worry less about the cost:benefit analysis. I can execute a small step, such as making a variable name more expressive or extracting a small method and re-run my tests to see if I’ve broken any code under coverage. I can stop with that one small change or I can continue.
If I find a large code base that is harder to refactor due to coupling, misplaced responsibility, or other issues, I use the Mikado method to map out where I can start.
So - When would I consider refactoring my code?
Always. I always consider it.
I try to refactor as I go. Write a test, make it pass, refactor.
I try to refactor to help me better understand a piece of code. Rename variables, extract methods, move things around. Refactoring helps me to understand what’s happening. Refactoring helps me see opportunities for more significant/beneficial refactoring.
I tend not to refactor code unless I am already changing it or need to change it for the current story. I tend not to refactor aspects of the code that are not relevant to the change I am currently making.
But sometimes I look at code that has recent churn and I spend some time refactoring it. Sometimes, I refactor just to make things better for future me and to make things better for my team.