DEV Community

Cover image for Writing Code Comments (Tips & Tricks)
Khaled Abdel-Fattah
Khaled Abdel-Fattah

Posted on

Writing Code Comments (Tips & Tricks)

🗨️Code comments serve as reminders for future developers trying to understand your work. A single comment before complex code can save time. Here are some tips for effective comments.🚨

Sure, here's your content converted into a numbered list:

  1. Explain the "Why", Not Just the "What": While good code often speaks for itself regarding its purpose, comments should dive into the reasons behind the chosen approach.

    • Code tells you how, Comments tell you why.
  2. Beware of Comment Overuse: While commenting is essential, it's also easy to overdo. Over-commenting can clutter the code, making it harder to read. Comment only when necessary to clarify complex sections or highlight non-obvious decisions.

  3. Give Examples: If something's tricky, a short example helps.

  4. Stay Updated: If you change the code, update the comments too. Don’t let them mislead others.

  5. Avoid Obvious Comments: Don't state the obvious. Like writing "increment by 1" for i++.

  6. Link to Documentation or Discussions: If the code relates to a specific architectural decision, bug report, or any other relevant discussion, provide a link in the comments.

  7. Explain the Intent for Future Changes: If you anticipate that a particular piece of code will need modifications or extensions in the future (due to evolving requirements, etc.), leave a note about the envisioned direction.

  8. Use TODOs and FIXMEs: Use TODO for things you plan to do, and FIXME for things that need to be corrected later.

  9. Don't Rely Solely on Comments for Code Quality: A comment is often a symptom of code that isn't clear on its own. Strive to write self-explanatory code, using comments to supplement, not replace, good coding practices.

Remember: Comments are like notes to our future selves and others. They should make things clear, not confusing. A smart comment today can save a headache tomorrow! 🧠

In wrapping up, always view comments as a tool to make the invisible visible, they bridge the gap between what the code does and why it does it. Aim for clarity. The right comment can make all the difference for the next reader, be it your future self or a fellow developer. Keep coding and commenting wisely! 🛠️📝

Top comments (0)