This is a problem I see a lot of people make even though their heart is in the right place. They see some code that is atrocious and they decide to refactor it. The thing is, that’s not always the correct choice. Just because some code is bad doesn’t mean it needs to be refactored. Before I explain why, I want to make sure we’re all on the same page about what it means to “refactor”.
To refactor some code means that you rewrite it but it has exactly the same behavior. If you change its behavior it’s no longer refactoring.
Now that we have that defined, I’ll explain when it’s bad to refactor some terrible code. It’s bad to refactor terrible code if it never needs to change. I’ll explain this with an example:
Lets say you’re trying to write a feature that sends an email when someone registers their account. Along the way you notice that the code to add a product to a cart is terrible. If you spend the time to refactor the cart code, it takes longer to add the feature that you need. If you had a crystal ball and could tell that the cart code would never need to change in the future, then that means you literally just wasted your time refactoring it. You could have been spending it working on features you do need.
Now the thing is you don’t have a crystal ball so you don’t know if it will change in the future or not. That’s why the best time to refactor some code is when it needs to change anyway. If you wait until the code needs to change then you already know the refactor will help. If you don’t know if the code needs to change, you’re potentially wasting your time refactoring it.
There is a caveat to this philosophy. If you’re working on a small code base, I’d be willing to refactor some code before it needs to change because it’s important to Fix Broken Windows. But in a large legacy code base, I’d follow the rule I just defined because there’s always more to refactor than there is time.