Learncamp by Mohit

Share this post
Code Comments
learncamp.substack.com

Code Comments

Jul 9, 2020
Comment
Share

Code comments have always been in discussion, whether one should have comments in code or not. Personally, I believe in not having comments and writing code in a way that makes things obvious. But, there are cases when you do want to add minor comments.

Be careful if you are adding comments, there is no way to check if your comments are correct or not!

In this post, I’ll be discussing when to use/not use comments in code -

When to use comments

Code Tells You How, Comments Tell You Why

  • Explain something which is not obvious to user like explaining architecture.

  • Adding TODOs for developing later

    func UserGetHandler(w http.ResponseWriter, r *http.Request) {            
       // TODO: Add google analytics     ...  
    } 
  • Documentation comments - for someone who wants to use your code but not really work on it. These are useful in generating documentation websites from code itself. Eg. Go libraries.

  • License comments - required due to legal issues.

When to not have comments

Best code comment is to not write it at all!

  • Don’t add comments which are redundant

// Import logger package 
import "github.com/google/logger"

In the above example, it is totally irrelevant to add the comment. Import statement already signifies what the comment says.

  • Avoid comments which can be code changes

func getSum() {       
    // initializing value as 10 - BAD!     
    valueOne := 10 
}
CommentComment
ShareShare

Create your profile

0 subscriptions will be displayed on your profile (edit)

Skip for now

Only paid subscribers can comment on this post

Already a paid subscriber? Sign in

Check your email

For your security, we need to re-authenticate you.

Click the link we sent to , or click here to sign in.

TopNew

No posts

Ready for more?

© 2022 Mohit Khare
Privacy ∙ Terms ∙ Collection notice
Publish on Substack Get the app
Substack is the home for great writing