Skip to main content

How to approach a refactoring job

We sometimes feel like the Ghostbusters. We get called because a business is haunted by a legacy, badly-written, unmaintanable code, pretty much like an old building may be haunted by an headless ghost. If you ever get in a situation like that (I mean legacy code, not ghosts) there are only a few appropriate ways to react, and they can be summed like this:

  • be prepared
  • don’t improvise
  • use the tools.

Be prepared

Maintaining and refactoring existing code is definitely harder than writing new code. Usually it’s written by someone else who just pushed the project out of the door as quickly as possible before moving on. Probably it was written for older versions of the language. And of course they never find the time or just didn’t dare cleaning and adjusting the inevitable mess. You need to be a seasoned professional and have a wide programming experience to be able to decipher and understand complex and obscure code.

Don’t improvise

Working with legacy code requires discipline.

  • You have to move slowly and thread carefully on what is probably a fragile structure. Don’t rush. After the inevitable WTF, try hard to understand what was the original purpose.
  • You must build a safety net of tests around the code, which may be already a significant undertaking as messy code is usually also harder to test.
  • You have to resist the temptation of starting big refactorings that cannot be safely tested, committed and deployed within a single session.

On top of everything, you should actually change and improve the existing code, not just apply another layer on top of it: that would just be a rewriting in disguise and – even if written with the best intention – will actually increase the overall existing complexity.

Use the tools

Now, don’t be so scared: you’re not alone and you’re not an adventurer. Dealing with legacy code has been done by many professionals during many decades now, and as a consequence there are tools to help you  with that.

First of all, there’s a lot of literature about it: you can read books like “Refactoring” or “Working effectively with legacy code” or just follow blogs like this one.

In software terms, the most important tool is a testing suite like PHPUnit or Mocha or similar tool dedicated to the language of your choice. There are also many additional libraries to deal e.g. with quickly building fixtures. There are tools like PHPmetrics that help you understand the overall status of the system and let you know what are the worst parts of the code. And finally, all decent editors should be able quickly reformat your code (because never underestimate how much tidying your code will make it more understandable).

Wrap up

We don’t fear ghosts and we don’t fear legacy code, because we’re professionals. There are methodologies, there are tools, you only need a bit of discipline.