The “Fix it or rewrite it from scratch” dilemma

I’m sure you found yourself in the situation of having to fix a piece of code that :

  • was not written by you
  • has not a clear set of requirements or the requirements are clear but the code is unnecessarily complex (at a first glance looks like you encountered the dreaded “big ball of mud”)
  • Nobody knows exactly the requirements anymore so you’ll have to reverse engineer from the code the behavior
  • Tests are missing or trivial and don’t help in understanding what that piece of code should do

My first question here is to understand where is the break even between fix and rewrite. I tend to prefer rewriting code if :

  • besides needing fixes there are also performance problems
  • code needs to be fixed/changed often
  • code is a company asset
  • code complexity is exposed to customers
  • coders turnover is high

Remember that :

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
— Kernighan and Plauger in “The Elements of Programming Style”

Let’s try to add some information. Pros and Cons for rewriting instead of fixing :

Cons :

  • Time/cost : rewriting takes time, probably more than a “quick and dirty fix”. The real cost analysis here is “how much faster would we make fixes if we had a clean code base?”. How many fixes we perform every year ?

Pros :

  • Coders will not have to work on a “big ball of mud” : this causes frustration and in the end lowers productivity (Time/Cost–)
  • New code base will probably be smaller (requirements sediments will get cleaned up), so less tests need to be maintained (Time/Cost –)
  • New code base will probably be faster (Cost–)
  • Newcomers will have short catch up time on the new codebase ( old codebase Time/Cost –)

So in the end all pros of rewriting lead to less time for maintenance/enhancements and less costs. In the end “Quality is Free” ( https://www.stellman-greene.com/2006/03/29/quality-really-is-free/ ) according to these guys.