October
2005
Refactoring good, rewriting bad1
Note: The following paragraphs were written a year before I became aware of Joel Spolsky wonderful writing on the same subject
“What a mess, this has to be written all over again”—be suspicious (very suspicious) when you hear someone (possibly your inner voice) says a piece of code has to be rewritten. Most of the time it is a symptom of incomplete understanding of the problem at hand or of the code you are referring to. Assuming the original code was not written by a complete idiot (which is more often than not the case) you’d better give it another shot.
On the other hand the “if it ain’t broken don’t fix it” mantra is dangerous also. Wiser men (than me, ESR for example) said that sometimes you only understand a problem once you solved it. Often the first iteration of the code works, yet it offers a less crafted design than you want (and now know how to do) or an awkward interface that messes things in your code or a problematic implementation (inefficient, inflexible, not thread-safe) that imposes limits on its users. Rewriting it sounds like a lot of work, but refactoring it sounds like much less work (even if the two coincide) and is probably what you should do.
Experience (mine) shows that refactoring is a much shorter task than rewritting especially since you have less bugs to deal with (and they are mostly known) and the testing process is much easier (as you already have real users or clients of the code). It is comforting to discover that such refactoring usually pays itself (in terms of development time and debugging) immediatelly and therefore should not be considered a task for a rainy day but rather a routine task. Problems that are noticed today but deferred are not likely to disappear, so when a major design flaw or incomplete implementation is discovered and ignored don’t be surprised to see its agly head pop up in some lesser expected places.
Nice work man