Lesson 3
Discovering your Paths
Chapter 10: Commenting
Good comments
How do you write good comments?
The answer is: it depends.
In general, your comments should be:
- useful/informative
- easy to understand
The level of detail of your comments depends on the context. Assuming that your code is self-explanatory (with a decent level of abstraction), your comments:
- can be more high-level (“
# searching for first time
”) - can be used to provide more details (“
# n must be between 3-10
”) - to explain the rationale behind why you did something (“
# this loop here is to ... because it is more efficient
”)
Basically, put yourself into the shoes of someone from the future trying to read your code.
If it is not clear from your code, document it with an intuitive explanation!
For example, this is too obvious. So don’t waste your time.
# Increment x by 1
x = x + 1
But this is more informative.
# Compensate for border
x = x + 1
This relates to the topic of abstraction that we discussed earlier.
If your code is already naturally highly abstracted and readable, then your comments will naturally be more high-level and intuitive, and will be aimed to provide useful additional context to someone reading your code in the future.
So, my general guideline is: if someone else (or your future self) might have trouble understanding bits of your code, then document your code with an intuitive explanation. Do not waste their (or your future self’s) time trying to figure out what your code does.