Good comments


Although the desire for good code is as old as code itself, it was Robert C. Martin’s Clean Code book from 2008 that made this name popular. His book compiles many good practices and recommendations that have been conceived and put to the test for many years, and it is considered by many, me included, as the point of reference when talking about what clean code is.

Particularly on this topic, I recently saw a post on LinkedIn saying how clean code was against comments and how bad this was. However, this is far from true. Although the Clean Code book discourages comments in general, it also gives very concrete examples of when comments are useful. In other words, clean code is not about not having comments at all, but about using comments wisely.

Clean code promotes code that is self-explanatory. This usually means that it can explain what it does, and sometimes it can even explain its domain. However, code can’t always explain the why of our changes. Comments can help in these cases:

def leap_year?(year)
  # We add a day every 4 years to match the solar year
  return false unless (year % 4).zero?

  # We skip centuries to avoid slow drift
  return true unless (year % 100).zero?

  # We add it back every 400 years to stay in sync
  (year % 400).zero?
end

Regular expressions are really useful sometimes, but they tend to be hard to understand. A comment explaining what it matches against can save a lot of time.

# Password rule: at least 8 chars with lower, upper, digit, and symbol
PASSWORD_RULE = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/

Comments are also extremely valuable to warn against unexpected side effects of changes to our code. For example, this comment let us know that changing to the default version of a configuration value will case troubles:

# Rails now defaults to :zone, but our application fails unless we use the legacy value :offset
Rails.application
  .config
  .active_support
  .to_time_preserves_timezone = :offset

I think that these cases are very reasonable situations when using comments is a good idea, and I strongly recommend reading the Clean Code book to learn about other cases when comments can be useful, and when they should be avoided.

However, comments tend to diverge from the code they relate to, so we should endeavour to write correct comments, and to update them along with their relevant code. Similarly, we should not blindly trust comments, as it’s a known fact that some of them will be out-of-date when we read them.

Cheers,
José Miguel

Share if you find this content useful, and Follow me on LinkedIn to be notified of new articles.


Leave a Reply

Your email address will not be published. Required fields are marked *