Programmers often complain that code they inherited, their colleagues wrote or even they themselves wrote in the past is “hard to read”, with the implied understanding that “the code is bad”. I used to nod my head, thinking “yeah, I know that experience” and not give it any more thought. However, at some point I realized that my belief that a lot of code I encountered was “hard to read” was just plain false.
I now believe that any unfamiliar code is initially “hard to understand”. Understanding doesn’t come through just reading code: it requires thinking about the code. Complaining that code is “hard to read” is like complaining that a different language you haven’t yet mastered is “hard to read”. The problem is your lack of fluency, not the text.
Reading through unfamiliar code feels comparable to reading through e.g. a book on Analysis to me. I may have the background to understand what’s there and can follow along, but by just reading it I haven’t understood it and I need to do the exercises to understand the consequences of what I read.
While investigating code, what usually happens is that I:
- discover what problem it actually intends to solve, as opposed to the problem I thought it solved
- figure out some complexities involved in solving that problem and stop underestimating it
- start understanding how the code addresses that complexity
- start understanding how a lot of the seemingly unnecessary complexity deals with relevant use cases and edge cases
- understand that the structure of the code makes sense, solves the problem and cannot be improved in obvious ways
So the code wasn’t actually intrinsically hard to understand: it was just hard to understand for me, because I understood neither the problem nor the structure of the solution.
Having realized this, what nevertheless still happened was that the initial “this code is incomprehensible” unfairly lingered in the back of my mind, contributing to a general sense of “all code out there sucks; we’re doomed”. I think that’s unfortunate and unnecessary and I’m happy that I’ve since been able to immediately follow up with “wait until you actually understand it before concluding anything” when I find myself thinking the code I’m reading is incomprehensible. Perhaps that would make you happier too?
Edit: retitled in response to feedback from lobste.rs. Thanks!