DEV Community

Discussion on: 5 easy wins to refactor even the worst legacy code

Collapse
 
ssimontis profile image
Scott Simontis

One of the hardest parts about refactoring a legacy codebase is not changing the meaning unless you have a test suite available. And let's be real, if it is a true legacy codebase, it either has no tests or there's a file where someone wrote three tests that barely make sense and decided to call it a day.

With #1, by changing the if to else if, you could change the meaning of the code by accident. In this example you are okay, but in other instances, you need to understand why the author chose a chain of if statements instead of else if statements. This could be part of the requirements cleverly hidden in code. I also believe that a switch statement is a much cleaner refactoring here.

For #3, the compiler should optimize out pointless write operations, so I would leave it up to the compiler to do its job and focus on trying to write tests for as much of the existing code as I can.

Sometimes with legacy code, I purposely make one to throw away. I take a copy of the source and refactor mercilessly and recklessly to try to make sense of everything. I will rename variables, comment all over the place, and make a ton of changes to get a better understanding of how things work. At this point, I have made too many changes to assure myself that no program logic has changed, so I delete it or at least set it aside. Even if I didn't make any lasting changes, the understanding gained is priceless.

Collapse
 
mlevkov profile image
Mikhail Levkovsky

unfortunately you are right. Legacy code and tests go like oil and water.
regarding #1, that's a great point that I didn't explain well (thanks for the feedback). If you write code that is chained that way, it leads to the next developer to guess why it was written that way.
It's the opposite of self documenting code.