Code comments can be used to document the design and functionality of a program and to provide instructions for how to use or modify a piece of code. They can also be used to indicate potential issues or areas of the code that require attention.
A helpful guideline when commenting on code is to focus on explaining the reasoning behind the code, rather than just describing what the code is doing.
Good code should be self-explanatory in terms of how it works, so it’s more important to provide context and explain the intent behind the code. This can help others understand the purpose of the code and make it easier for them to work with it.
Code comments best practices:
- Make comments meaningful.
- Comment on your classes, methods, and functions.
- Use clear and concise language.
- Use correct grammar and punctuation
- Be consistent with your commenting style
- Include reference links when relevant.
Things to avoid when writing code comments:
Comments in code should always be kept up to date. They should accurately reflect the current state of the code in question. If you make changes to a portion of code in a project, you should update the comment accordingly. A few things to avoid when writing comments in code:
- Don’t use comments to explain flows. Don’t leave “To-Do” comments.
- Don’t write comments in the wrong place.
- Don’t comment out code.
- Don’t over-comment.
Comment conventions:
- Do not add empty comments.
- Begin single-line comments with a single space.
- Single-line comments should always be preceded by a single blank line.
- Single-line comments should never be followed by blank line(s).
- Do not write embedded comments.
- Do not write comments between declaration of statement and opening curly brackets.
- Place comments above statements, or within statement body.