Executable Comments
By: Johnathon Wright on: October 07, 2020
One of the most important skills that differentiate an upper-mid-level developer from a lower-mid-level developer is the ability to write readable code. One strategy for increasing the readability of your code is to use something I've heard referred to as "executable comments" -- writing your code so that the variable names and structure give the reader maximum comprehension of the logic you're encoding.
Here is an example:
if roles.any? {|r| r.requires_segment? } && self.store_id.nil?
errors[:store_id] = 'is required for users with these roles.'
end
If you aren't familiar with Ruby, this syntax can leave you a little confused. But translated into English, it would be "If there are any roles that require segments AND there is no store_id." And I can make the argument that it's fairly readable. As a loosely-typed language, Ruby tends to lend itself to readability already. And the names here are already evocative, semantic names. The structure is relatively simple. But consider this slight change:
segment_required = roles.any? {|r| r.requires_segment? }
if segment_required && self.store_id.nil?
errors[:store_id] = 'is required for users with these roles.'
end
Adding that variable means that each line is just about as simple as it could possibly be. I don't think any of those lines could be broken down further, or any context added, that would improve comprehension. It requires a bit less mental energy to parse per line / per bite. And that makes the code dramatically easier to understand.