/
Code Comments

Code Comments

This seems to somehow be a topic of debate between developers. Everything I’ve written here is my idea of an ideal guideline, which I try to stick to but often fail. I think collectively we’d benefit from following some guidelines on code comments, if anything for our own future benefit, as well as others on the team.

Useful articles:

Code Tells You How, Comments Tell You Why

Comment Only What the Code Cannot Say | by Kevlin Henney | Medium

The basic gist of these articles and my own experience boils down to this:

Code tells you what, comments tell you why

Clean, well written code should largely explain what is happening by itself.

For example, take this Python snippet:

for index, value in enumerate(value_list):     if index < 100:         print(f"{value} at position {index}")

Many of us will often, almost out of reflex, add comments like:

# For each element in the value list for position, value in enumerate(value_list):     # Check if the index is within the first 100     if position < 100:         # Print the value and it's position         print(f"{value} at position {position}")

We’ve added absolutely nothing of value here though. Even a glancing understanding of the language makes everyone one of these comments a waste of space.

A more useful comment would explain why we do what we do, for example:

for position, value in enumerate(value_list): # Only the first 100 values will be entered into the ballot. Discard the rest. if position < 100: # Print the values to stdout so entries can be verified by-eye print(f"{value} at position {position}")

 

These comments now provide information not available from the code itself. We’ve actually added something useful.

What about really complex code?

9 times out of 10, if the code is complex enough that comments are needed to explain what it happening, the code should be refactored.

For example, our code snippet above would work just fine1 awfully rewritten as:

 

However since it’s so much less readable it would be tempting to just add a bunch of comments explaining what’s going on. By the time you’ve done that though, you may as well just rewrite it in a clearer format.

1 I’ve never actually tried this code, so it may not actually work, but it demonstrates a point