Why Refactor?
posted on: Sep 15, 2019

As a developer, once I get a feature working, the common impulse is to move on to a next shiny feature. However, programming is so much like writing. Getting a feature working is just a first draft. You have to come back to it and rewrite it and refactor it. Martin Fowler’s new book lists the following benefits of refactoring.

Refactoring improves the design of software. Without refactoring frequently, the internal design starts to decay. As we change code to achieve short-term goals, without grasping the overall architecture, the code loses its structure. Regular refactoring helps keep the code in shape.

Refactoring makes software easy to understand. When I am in the rush of writing code, I am not thinking about the developer who will be reading the code in the future. If I have a program that works, but is poorly structured, badly formatted, and poorly named., I am not showing empathy for that future developer, often myself. Refactoring helps to keep the code more readable.

Refactoring helps you find bugs. Once you refactor the code, you often see the hidden bugs lurking beneath the surface. Often I realize the numerous null reference exceptions once I extract a method from a bloated piece of code. To refactor code, I need to understand the code, which often helps to figure out all the ways it could go wrong.

Refactoring helps you program faster. Often, the initial investment made in refactoring code pays huge dividends in the future. It’s counterintuitive, but refactoring helps you save more time in the future. When you come back to the code after six months and you don’t have to spend few hours, trying to figure out what you meant when you wrote this piece of code, that’s where the real benefits lie.

If you don’t refactor frequently, sure, you can ship more code; but every new feature will take more and more time to understand how to fit it into the existing code, to the point where you can’t add any more code and have to throw away everything start from scratch, which is probably a very bad idea.