Refactor your legacy code with confidence

Tarek Djebali
3 min readSep 21, 2020

--

Refactoring legacy code is … Well! let’s say not the most exciting task for a developer. It’s even considerer by some to be a scary one. 😱

A tempting solution would be to lower the priority of the task and push it to the deep end of your backlog!

Why on earth would you change a working system? And risk the introduction of new bugs!!! — A scared developer.

Well! It sounds like a valid argument, but!

  • Are you sure that those bugs don’t already exist in the code?
  • What if it’s the last task remaining in the backlog! 😅 😏

In this article, I’ll give you 2 rules that, in my opinion, will make your life easier.

Rule #1: Never refactor without tests. NEVER!

Tests will get your back. It will ensure that you do not introduce new bugs while changing the code.

Source: http://gph.is/1UqElxW

If your code is already tested you are lucky! Your team covered you back. Go ahead and break stuff confidently! 😁

But most of the time we don’t have this privilege. We have to do the dirty work ourselves! No worries! Tests should not be perfect because remember! The goal is to have something that validates our changes.

It doesn’t matter if your tests are slow to run, or don’t follow Unit testing best practices. What matters the most is that you have an indicator that your changes don’t break things.

Oh! And by writings tests, I mean for the peace of code that you are about to change. Which lead us to the second rule.

Rule #2: One small step at a time

Don’t be tempted by big changes! Go by small portions. Let’s imagine we have a giant PHP file containing a few dozen of procedural functions that we need to convert to OOP.

Bellow the steps that I’ll follow:

  1. Create a Utility class.
  2. Pick a function
  3. Write a test for it and ensure it passes.
  4. Copy the first function as is to a method in the Utility class.
  5. Mark the old function as deprecated and make it invoke the freshly created one.
  6. Ensure the test passes.
  7. Optimize / Change the method code.
  8. Ensure the test passes.
  9. Go to 2. and repeat
Flowchart of the process

The next step would be to divide the Utility class into multiple classes by responsibility for example. Anyway! You get the idea: Split the main task into smallest pieces you can.

It’s a wrap!🎬

That’s it! I hope that this quick post will help you be more confident the next time you have to work on legacy code.

Remember those two rules :

  • Write tests before any change.
  • Small bite at a time.

Enjoy your next task! 👋

--

--