The Dangers of Refactoring Legacy Code

Refactoring legacy code can be dangerous.

  • There is no automated way to verify changing that code doesn’t break something.
  • The person that wrote the code may not be at the company, or he doesn’t remember what it does.
  • It uses old technology that is difficult, and people don’t have expertise with it anymore.

So when someone does have the courage to improve the code, they may introduce a very big bug that doesn’t get detected until it gets shipped to the customer.  This leaves the developer that was brave enough to make things better look and feel bad.

Shaking My Head

This leads to really bad culture.  People are literally scared (although they won’t say this) to change sections of the codebase.  Legacy code increases your technical debt, so it is harder to add features over time.  And since people are scared to change that code, it gets worse and worse.

Hands down, one of the best books I’ve seen on dealing with legacy code is Working Effectively with Legacy Code.  This book discusses some ways of dealing with code that is not already wrapped by tests:

  • Dependency injection
  • Refactoring into functions
  • And much more

I am not going to specifically talk about working with legacy code in this post.  As can be seen with that book, tons of material can be written on how to prevent yourself from creating bugs in code that is not tested.  Rather, I am going to point out another reason you should be writing unit tests/automated system tests with your code.

If your code is going to be around for quite some time, technologies will probably change.  People will look at your code after months or years (but hopefully not right after you write it!) and not understand anything about it.  They will have to read it for a while and play with it to understand what it does.  Perhaps it will be time to refactor it.  That being said, how will they know if they break existing functionality?  Without existing tests, it’s going to be extremely difficult.

So in order to make your code stand the test of time…

Time

TEST IT!  (with automation)

Write unit tests or automated tests around your code.  Maybe you “don’t have time”, as doing so would make you late to market.  If that is your excuse (yes, I used the word ‘excuse’), take the time after it is shipped to test it so future features added to it are more reliable.

Untested code, even if just written, is legacy code.

Do yourself and your company a favor when writing code – add unit tests and/or automated system tests.  Make it clear how to run them.  This is an investment in you/your company’s future.  When future work has to be done with that code, it will be more reliable and easier to refactor due to your due diligence.

Leave a Reply

Your email address will not be published. Required fields are marked *