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:
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.
Working with legacy code requires discipline.
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.
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.
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).
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.