will warnock

auckland, nz

Chesterton's Fence in Codebases

Like many programmers, when I see something that looks janky in a codebase I have an innate desire to fix it. Whether it's an unnecessary API call, a verbose expression of logic or a piece of code that isn't quite pythonic, my initial reaction is to improve what I'm looking at. This mindset leads to better outcomes when I'm working with code I understand, but it has burned me when navigating codebases that I'm unfamiliar with.

While debugging foreign codebases I am often distracted by odd looking sections of code. An error handler that doesn't appear to be handling anything, or a redundant function for example. I'll typically find a fix for the original issue that I was looking for and also remove or refactor some of the code that I think needs improving.

Unfortunately, especially in my early days of programming, I would find after a few weeks that I created another bug when I haphazardly "tidied up" those janky-looking lines of code. I saw them as obvious and objective improvements, without really considering why they existed in the first place. G.K. Chesterton laid out this very idea way back in 1930, and I particularly like its parallels to software development today.

"... let us say, for the sake of simplicity, a fence or gate erected across a road. The more modern type of reformer goes gaily up to it and says, “I don’t see the use of this; let us clear it away.” To which the more intelligent type of reformer will do well to answer: “If you don’t see the use of it, I certainly won’t let you clear it away. Go away and think. Then, when you can come back and tell me that you do see the use of it, I may allow you to destroy it.”
Fence Painting

The application of this idea to software development is that you shouldn't remove or refactor any code before understanding why it was written in the first place. Taking extra time to understand the original chain of thought as to why an unorthodox approach was taken will help to come up with more efficient and effective solutions. Too often I have decided to rewrite something myself only to find that my final output is almost identical to the original code that I had set out to improve, because I understood why the author made the decisions he/she did as I made them for myself.

So the next time you have that urge to fully rewrite someone else's code, take a minute to understand the constraints they were under and try to come up with a rational as to why they approached it in the way they did. And if you are the person frequently solving problems in atypical ways, leave the rest of us a comment or two so our brains don't rot trying to get inside your head.

1It sounds like a yarn, but I will very regularly stumble onto lines of code and wonder who wrote such garbage, only to check that the author was me.