The Code of Christmas Past
When we write code, we’re often thinking about the short term. We need this code to function correctly so we can deliver within our immediate deadlines. I’ve found it important to also think of the long term. Sooner or later, we might encounter our own code, again.
I spent a chunk of my career where I often worked solo on projects that might get enhanced every year or two. This taught me a lot about the importance of code readability and what sort of things helped me quickly understand and avoid overlooking important considerations. I’ve also worked on a lot of legacy code bases, so I’m well aware of the pain and problems created by code that’s not readable, or is not organized in a helpful manner.
Last week at the AgileDC Conference, someone told me they were working on code I had written ten years ago. My first question was, “Are the unit tests still working?” This code was the first production code I ever wrote test-first, and it taught me a lot doing so. I was glad to hear that they had been maintained. When I was writing them, I couldn’t get anyone else interested in test-first development.
Even more gratifying was hearing that they’d recently used some of my code as an example in a discussion of object-oriented programming. The example they’d used was where I’d wrapped an integer in a class. Why would I do that? Because it wasn’t really an integer. It was a database ID. The integer was just an artifact of the database automatically creating ID values using a sequence. It would make no sense to perform arithmetic on it. And there were IDs for various entities that should not be used interchangeably.
The integer value was intended to be used only within the Data Access Object that read and wrote the database.
A few years ago, I was asked if I could change an algorithm in some embedded assembly code that I’d written more than ten years prior, and I hadn’t even seen for over ten years. Setting up the development environment wasn’t easy, as much of the hardware was no longer manufactured. The code, however, was not hard to modify. I had implemented the algorithm using state machines and data tables, and had created semi-readable constants for all of the “magic numbers” used.
Code is read much more frequently than it is written. Writing it clearly and expressively pays off when we have to read it next week or next month. Well-written code is also much more likely to be useful for decades into the future. If you write code only for the short term, it’s likely to have only a short life. People will find it necessary to rewrite it rather than maintain it for the long term.