We all refactor when we shouldn’t. It’s just a fact.
I recently attended a Women Who Code meet-up about this very thing, called “Refactoring Dos and Don’ts”. Stefanie Diesi gave some great reasons to refactor, or to not refactor, that I think would be a good reminder to all of us, no matter how long you’ve been in the industry.
Reasons to Refactor:
- Repeat offenders
- Refactor when there is code duplication and you are fixing the same bug or making the same upgrade in multiple places
- Do it in small steps!
- You want to refactor when you can “draw a box” around the duplicated code, so that you don’t spend too much time, or get too much feature creep in your refactor. If you can’t draw that box, then don’t do it!
- Fragile code
- “Bandaids on top of bandaids”… when a bug fix introduces a new bug, it’s time to refactor.
- Make small changes and document them
- By this point, you may not have the time, which is why you want your changes to be as small as possible.
- Dramatic build reduction
- Reduced build times increase development cycle.
- It is beneficial to refactor if you can improve the time “enough”
- While I love this chart from XKCD, it changes a little if you are consulting like we do here at Radial. While saving 5 minutes 5 times a day would generally be worth spending 4 weeks to do, if you have a 6-week contract with a client, then it’s obviously not worth it. Just be smart about what you decide to spend your time on.
- Major feature request
- The new feature doesn’t fit into the current architecture, so it’s time to refactor.
- This is an exciting reason to refactor, especially if someone has agreed to pay for it!
Reasons NOT to Refactor:
- Annie Oakley excuse
- If you’re saying things like this, you just shouldn’t do it
- “Anything you can do I can do better”
- “This code is terrible”
- “This code is so hard to understand”
- “I could write this so much better”
- Remember, the worst developer is you 6 months ago. If the code is works, just don’t touch it. You probably don’t have the time, and you’ll come back to it in 6 months and just want to re-do it again. This is a never-ending cycle.
- If you’re saying things like this, you just shouldn’t do it
- I <3 Code
- Yes, we all love writing new code, but that’s not a good reason to refactor. You don’t always have the time to refactor like you should, so it’s best to leave it be.
- Learn by doing
- So you just learned about this super cool new tool, technique, language, pattern, etc. You think “I’ll refactor this code and use this new thing!” STOP! Do not use refactoring as an excuse to learn something new.
- The enemy you know is often better than the enemy you don’t.
- There are known knowns, known unknowns and unknown unknowns.
- Gold plating
- Don’t add features above and beyond because they might be used “someday”
- This is unnecessary and often not appreciated.