Jérémie Bonal


Legacy code

What it is and what we can do about it.

Legacy code is the bane of most developers. But it is a reality we all have to deal with.

It’s code you’ve inherited from someone else, maybe from way older versions of your app. And often it comes without any proper documentation, a lot of smells, and a nagging feeling that “we should probably rework this… but it works as is though”.

I’m sure that some developers will spend most of their time on relatively new codebases, ones they will build from the ground up — and that they’ll never deal with legacy code as such.

Even then, I’m of the opinion you can inherit legacy code from yourself — or more accurately from “5 years ago"-yourself.

I remember getting to use code that was seemingly constructing a very long string, based on a lot of options, parameters and collections. And then, it eval'd it.

When I went to see the colleague who built the library, turns out that at the time they just didn’t know how much metaprogramming you could do in Ruby without ever needing an eval call.

Some other parts of the code were straight-up reimplementation of things the framework could do by itself. “We started 8 years ago with version 1 dot something" — we were now at version 4.2.

Time makes foreign all things, I guess.

I should clarify, legacy code is not bad code per se. It is only old, or a bit more complex than it should and the author is nowhere to be found.

I hated it.

And I think that’s the approach we tend to have most often towards legacy code. We tend go nuclear, rewrite it all and damn those who came before us.

Turns out that’s not so great.

Lack of pre-written tests, lacking comprehensive knowledge of the code being rewritten and poor structure in our refactoring operations often leave us with a mess of code that only seem better to us than the previous one because this time, it’s made by us.

I’ve left behind me quite messy code. Which then turns into its own legacy code.

What to do then?

It turns out, dealing with legacy code is not spring cleaning. It’s more like improving your environment. You upgrade parts of it, one by one, whenever you stumble upon something whose improvement is in your capabilities.

It’s writing a test for that modification you had to make on that one old library, it’s annotating bits of hackey code after spending a while figuring them out, it’s replacing that one while loop by a for or an each.

Legacy code is never a business priority. Trying to make it one will often turn it into new, soon-to-be legacy code. Let’s just factor it in our task estimates and do whatever little we can whenever we can about it instead.

More by Jérémie Bonal

Topics of interest

More Related Stories