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.





Comments:

Just checking that you are human. What would be the result of this code?

a = 3*(4/2); b = 1; a+b

Eli said: One option is to purchase a separate insurance policy from a third-party insurer. This type of policy can provide more comprehensive coverage for your belongings, including protection against theft, fire, and natural disasters. Some moving companies even offer these types of policies as add-ons to their standard coverage. https://www.youtube.com/watch?v=-PirMZp5nCM

Peter Kyle said: This means structuring your code and choosing variable names that clearly convey the logic and purpose of the code, making it easier for others (or yourself in the future) to understand what the code does without needing additional explanations. https://sustainable-empowerment.co.uk/

Back