Day 3: How to write good code comments?

Commenting involves placing Human Readable Descriptions inside of computer programs detailing what the Code is doing. Proper use of commenting can make code maintenance much easier, as well as helping make finding bugs faster. Further, commenting is very important when writing functions that other people will use. Remember, a well-documented code is as important as correctly working code.

Today, the challenge is to share one essential thing to consider when code commenting. You should nominate another one after posting yours.

Keep them short

Comments are controversial, so the shorter the better:

// we need this to set up the user's permissions for v3 auth method
# should be
// set user permissions for updated v3 auth

I nominate @piumal1999 :face_with_hand_over_mouth:

1 Like

Don’t make redundant comments
A redundant comment is a comment that is not more informative than the code. It does not justify the code or provide intent. These comments only clutter the code.

// Method that return true if when stream is open
// Throws an exception if stream is closed
public function waitForStreamClose() {
    if (!$this->closed) {
        return true;
    }
    throw new Exception('Stream still open');}

I nominate @anjisvj

1 Like

Always start with a capital letter
When you are writing a comment always start with a capital letter.

ex:
:white_check_mark: correct
// This is a comment

:x: incorrect
// this is a comment

I nominate @Gravewalker :yum: to continue.

2 Likes

Don’t put already available information

Don’t write a story in the comment as your name, employee id, your department, etc because that information can be obtained from Git commit data in case someone wants to know who has made this change.

I nominate @Janeth_Fernando

1 Like

Never denigrate the author
In open-source projects, I have seen comments which are written to denigrate the real author. For an example look the following comment.

//This function looks like it was written by a third-grader.
//It shouldn't work, but it does somehow. I don't want
//to fix it because I want you all to see how bad it is.

We should never do this. Even if you think you’re being funny or that it makes you look good, it isn’t and it doesn’t.

I nominate:- @Yohan :grin:

2 Likes