Thursday 14 June 2012

There's Never a Good Time to Refactor

I guess that's why they call it eXtreme Programming.

The problems with refactoring code almost always seem to outweigh the benefits. There's not enough time in the plan, it works fine as it is, we'd need to completely regression test it, etc. etc. The problems (or excuses) are well versed and easy to reel off whenever the question of a major code refactor comes up.

The benefits are less obvious; more testable code and easier maintenance are the usual candidates, and they sound like small change in the face of all the problems mentioned before.

The thing is, while the "problems" are a one time hit, the benefits multiply every time you touch the code. As do the downsides of not refactoring! Every time you go back to that bit of code and change it, you'll have to do a bit more work than if you'd refactored it before. On top of that, every new change probably makes the refactoring case even stronger, until eventually, it can't be put off any longer and the refactoring work finally gets done. Only now, the code has more to it so the refactoring takes longer, which added to that the extra cost of each change up to that point, means the cost of not refactoring has suddenly become significant!

If we'd refactored up front, then subsequent changes to the code might have been easier, quicker, and we might also have a suite of unit tests that could provide us with a level of confidence in our changes that we previously didn't have. Suddenly the problems of yesterday don't outweigh the benefits at all.

So it's true, there really never is a good time to refactor, so don't delay, cut your losses and get it done now.

No comments:

Post a Comment