Evaluating code readability is actually pretty easy. I’ll explain it in a way that you can easily illustrate with a flow diagram. And you can see if you agree with my assessment.
- Did someone else write this code? If so, it’s not readable.
- Did I write this code but more than six months ago? If so, it’s not readable.
- Otherwise, it’s readable.
Sound about right?
I kid, but only kind of. This tends to be my visceral, subconscious reaction before I reign myself in and think rationally. And I bet the same is true for a lot of you reading as well.
Code Readability and Subjectivity: the Elephant in the Room
This happens because of the inherent subjectivity involved with the idea of code readability—or, more specifically, with the idea of readability in general.
To understand what I mean, let’s use an extreme to make a point. I could write a few lines of C# that just about any programmer reading would understand at a glance. But a non-programmer or neophyte programmer might read it and fail to grasp even these basics.
“What does ‘return’ mean?”
So readability depends on your prior knowledge and your perspective. And frankly, it also depends a lot on your own preferences. Some folks seem to like compact, dense code while others favor frequent empty lines to “space things out.”
What does all of this add up to? Well, it means that we cannot possibly tackle this subject without acknowledging the opinion-based and subjective nature of it. But that doesn’t mean we shouldn’t address it.
A Loose Framework for Discussing Code Readability
I’m going to spend the rest of the post offering my opinion on how you can make your code more readable. But before I do that, let’s reframe slightly. Let’s think of code readability as time to comprehend.
Of course, time to comprehend doesn’t eliminate subjectivity. But it does introduce a measurable concern that we can use as a metric. So, for the rest of this post, I’ll talk about code readability in terms of time to comprehend, with the following guidelines:
- We’re talking about time to comprehend for a developer in the language of average experience.
- Matters of preference and familiarity will affect this time to an extent, but so will various language properties.
- Code readability is generally preferable, but not in all cases (e.g., you might have need to optimize a critical path where advanced language usage and other concerns trump readability).
Now, all of this is still my opinion about code readability. You’ll have your own opinions, of course. But it’s through this lens I offer you the following tips on how you might evaluate and improve code readability.