When and How to Refactor Code
First off, if you haven’t heard of them already, allow me to introduce you to these popular rules of code optimization. Take a minute and check ‘em out.
Those rules apply perfectly to code refactoring. So, before embarking on a journey that will cost you a few weeks worth of work, don’t, don’t yet, then make sure the time spent will be worth it.
The decision to refactor code, like everything in life, is a judgement call. But if you’re already thinking about refactoring a piece of code, chances are it will happen eventually. What remains to be determined is the when and how.
Code refactoring should start when the code is being written, not when it’s stinky and ugly.
Here’s one of my favorite quotes from a friend about technical debt, the primary cause for refactoring:
What you’re building right now is technical debt in the future.
Take a minute and absorb. That means whatever you do, code you’re writing today will be outdated down the line. So instead of spending your time building the perfect piece of software, you should spend your time making that piece of software easy to improve. For example, don’t spend your time iterating between two designs that have minor differences. Rather, spend your time writing tests for your program, that way, if you ever decide to go with a different design, it’s easy to switch.
What made Michael Jordan great? He had sound fundamentals – crossover dribble, head fake, jump shot, swish – and that’s what made him a great player consistently. Focus on the basics:
Always leave code in better shape than you found it.
Constantly applying that rule will put you in a position to never have to budget a few weeks into your project planning purely for “refactoring code,” whatever that means. Focus on your and your teams’ fundamentals and make sure all engineers are building towards the same final design; pair programming is good for that.
Finally, to carry out the advice above, keep agility on your side. This will help you avoid big refactoring projects and encourage small, more frequent refactorings. Invest in your tests CI tools so you can encourage engineers to always leave code in a better place than they found it. If you have high test coverage and fast tests, you’ll worry less about modifying legacy code – now, wouldn’t that be nice?
Shippo is a multi-carrier API and web app that helps retailers, marketplaces and platforms connect to a global network of carriers. Businesses use Shippo to get real-time rates, print labels, automate international paperwork, track packages and facilitate returns. Shippo provides the tools to help businesses succeed through shipping.