What are the guidelines for adding comments in source code? When is it necessary to include comments?
Adding comments to source code is an important part of writing clean, maintainable, and understandable code. Here are the guidelines and when it’s necessary to include them:
✅ Guidelines for Adding Comments
- Be Clear and Concise Keep comments short but informative. Use complete sentences if needed, but avoid rambling.
- Explain "Why", Not Just "What" Good code explains what is happening. Comments should explain why it’s happening—especially for non-obvious logic or design decisions.
- Avoid Redundant Comments
# Increment i by 1 i = i + 1 # <- This is obvious and unnecessary
Instead, only comment when the code’s purpose isn't immediately clear. - Use Proper Grammar and Punctuation Especially in team environments—treat comments like documentation.
- Keep Comments Up to Date Outdated comments can be worse than no comments at all.
- Use TODOs and FIXMEs Sparingly Clearly tag work that needs to be done. Example:
# TODO: Refactor this loop to improve performance
- Comment Code Blocks, Not Every Line Avoid cluttering the code; summarize what a block does instead of annotating every line.
- Use Docstrings for Functions and Classes Especially for public APIs or anything reused. pythonCopyEdit
def add(a, b): """Return the sum of a and b.""" return a + b
- Stick to a Consistent Style Follow your team’s or language’s style guide (e.g., PEP 8 for Python, Javadoc for Java, etc.).
🟡 When It’s Necessary to Include Comments
- Complex or Tricky Code If the logic is clever or non-intuitive, explain it.
- Workarounds or Hacks Mention why a workaround was necessary and what limitation it's addressing.
- External Dependencies Note where the code relies on third-party behavior or versions.
- Business Logic Explain decisions that stem from business rules, especially if they might change.
- Assumptions If your code depends on specific assumptions, document them.
- Interfaces and APIs Always comment public methods, expected parameters, return types, and side effects.