Unconventional Programming Tips: Comments

TLDR: Best comments are written when you read the code - not when you write it.

Random thoughts on programming

I was recently reading Best Practices for writing code comments by Ellen Spertus. While there are some helpful tips, it misses the most important ones for me:

  • Add “why” comments when you write the code.
  • Add all the other comments when you read the code.

What is the main purpose of comments?

They should help me understand the code easier. More than often, when I write the code, it is immediately clear what I was trying to solve. I have the context and the reason for my decisions are freshly in my mind.

Few days later, re-reading the code, I don’t know anymore why I wrote the code like that. That is when I add the most valuable comments. Many people tell you not to duplicate code with comments, but if it makes it easier to understand the code - why not? Don’t follow any advices blindly - even the above ones.

Consider this example:

while (element.parentElement != null){
  // do some stufff

while (element.parentElement != null){ // we didn't reach root
  // do some stufff

On a daily basis, I don’t tend to write many while loops. That makes while loops not always easy to grasp. If I encounter one, it is not very easy to understand the conditions. In the above case, the condition is simple, nevertheless the added comment improves the code quality for me. I don’t have to focus on the condition, I can read the inner parts knowing they are executed until we reach the root.

In many cases, null checks are another good example. Null has so many semantics. When I write the code, I know the meaning of a variable being null, but when I read it again, it is not clear what the initial reason was:

  • is it because null means the value has not been set?
  • is it because null means the value was there, but has not been set?
  • is it because null means the value is invalid?
  • is null the expected value?

Try to add a comment why you expect null. You don’t have to add it each time - only in the cases where it is not clear from reading the code.