Rewrite or Refactor
Often, inexperienced programmers will come to a point where they decide that their existing code base is fatally flawed in some way. Perhaps they’ve learned some new techniques that cannot be cleanly integrated into the code, perhaps they’ve stumbled across a requirement they cannot address, or perhaps they simply don’t like the naming conventions they used.
Whatever the reason, the programmer will often decide that the solution is a complete re-write of her code base. “This time,” she says, “I’ll get the design right the first time! My new code will be better, cleaner, more robust, more generic, and overall more powerful and less buggy!”
Unfortunately, this is wrong. Rewriting your code from scratch is very often a bad idea. A developer who is uncomfortable with the state of her code should refactor it, not rewrite it. The key difference between the two is that refactoring is about making many, usually small, iterative changes to the existing code in order to make the old implementation conform to a new design. Ideally, one would preserve the ability for the code to compile, run, and/or be consumed by client code as much as possible, within reason (adopting a new design may, of course, involve breaking the public interface of the subsystem).
Why is refactoring better? Refactoring actually forces you to think about the problems. It forces you to look at the current design, the current problems you have with that design, and what you could do to address those problems. When you don’t think about the problem, and choose instead to nuke the entire subsystem from orbit and rebuild from scratch, you’re probably just going to make the same mistakes again; you’re rewrite will most likely be superficially different from the original (for example, you might have more consistent or different looking naming conventions), but nothing more. Refactoring allows you to learn from your mistakes. Rewriting just blissfully ignores your mistakes, all but ensuring history will repeat itself.
Refactoring is an important skill to master. In the real world, full-on rewrites of existing subsystems are almost never cost-effective, so refactoring ends up being the only real sane option.
