1

Unconventional Programming Tips: Comments

 2 years ago
source link: https://dev.to/kiru_io/unconventional-programming-tips-comments-cc0
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Kiru

Posted on Nov 18

Unconventional Programming Tips: Comments

Originally posted on my personal blog.

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
}
Enter fullscreen modeExit fullscreen mode

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, while 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.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK