Code Comments
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
}