Mastering the Art of Code Comments: 9 Essential Rules

Giulio Rusciano
6 min readNov 18, 2023

--

Have you ever come across a code that was so confusing that it looked like you were trying to decipher a text from a long-lost civilization? Well, fear not! This article is here to help you navigate this essential aspect of coding: comments.

Whether you are a beginner or an experienced developer, knowing how to write clear and concise comments can make all the difference in your projects. Sometimes they mark the difference between a professional engineer and an amateur.

High-quality code should embody the clarity and elegance of finely crafted prose, with inline comments serving as its illuminating annotations. Unfortunately, the significance of crafting insightful comments is frequently underestimated, relegated to a secondary or trivial role. However, neglecting to provide thoughtful comments, or offering ones that are unclear or absent, can perplex or misdirect the reader, potentially causing greater confusion than the absence of comments altogether.

Many developers forget that they are not coding for themselves, but that their job is to provide error-free code that is also understandable and maintainable for the rest of the team. Writing code for the sole purpose of being unnecessarily complex and convoluted may make the developer feel smart for a fleeting minute, but it can create bigger problems than it solves.

Photo by Artur Shamsutdinov on Unsplash

Ellen Spertus meticulously delineated an exemplary framework, providing invaluable insights on the art of crafting effective and precise code comments. You can find it here

To sum up…

Rule 1: Avoid Redundancy

Effective comments serve to elucidate the reasoning behind the code, provide insights into its functionality, or offer context that may not be immediately apparent. Redundant comments, such as the example

i = i + 1; // Add one to i

contribute little to enhancing understanding and, instead, introduce superfluous noise into the codebase. It is crucial to prioritize comments that add value by clarifying complex logic, outlining algorithms, or explaining design decisions, ensuring that the code remains both comprehensible and maintainable for developers who come across it in the future.

Rule 2: Clarity Over Comments

When faced with the inclination to append comments to elucidate a convoluted code block, it serves as a crucial signal to pause and reconsider the code structure. Prioritize refactoring the code to enhance its clarity and simplicity. Thoughtful variable naming, in particular, can often render comments unnecessary by conveying the purpose and functionality of the code elements more intuitively. Striving for self-documenting code not only fosters readability but also mitigates the need for excessive comments, resulting in a codebase that is more maintainable and comprehensible for both current and future developers.

Rule 3: If It’s Complicated to Comment, It’s Likely Wrong

A lack of clarity in composing a comment for a code segment can be a telltale sign of underlying issues — perhaps the code is overly intricate or the logic entangled. This ambiguity serves as a red flag, indicating the potential need for a comprehensive code overhaul. Consider restructuring the code to simplify its complexity, unravel convoluted logic, and enhance overall readability. Striving for clarity in both code and comments not only fosters better understanding for yourself and others but also serves as a proactive step towards maintaining a robust and sustainable codebase.

Rule 4: Clarify, Don’t Confuse

Avoid allowing your comments to morph into perplexing riddles. A well-crafted comment should serve as a beacon of clarity, shedding light on the intricacies of the code rather than shrouding it in confusion. If a comment leaves readers with more questions than answers, it signals a deficiency in clarity and helpfulness. Strive to provide comments that offer meaningful insights, explanations, and context, ensuring that they act as informative guides rather than enigmatic puzzles for those navigating the codebase.

Rule 5: Comment Unidiomatic Code

In certain scenarios, deviating from conventional coding norms becomes a necessity to address special cases. However, when such departures occur, it is imperative to provide a clear rationale through explanatory comments. These comments act as essential signposts, guiding future developers to understand the deliberate deviations and preventing well-intentioned but potentially misguided attempts to “fix” code that is intentionally designed for specific circumstances. A judicious use of comments in such cases not only preserves the integrity of the code but also facilitates collaboration by ensuring that subsequent developers are informed about the deliberate deviations from standard practices.

Rule 6: Attribute Copied Code

When incorporating code snippets from sources like Stack Overflow, ChatGPT, or any other platform, it’s imperative to include a link to the original code (whenever possible). This not only provides crucial context for understanding the code but also ensures compliance with licensing agreements. Transparently attributing the source, developers can readily access additional context, discussions, or updates related to the code. Moreover, this practice upholds ethical standards, promotes a collaborative coding culture, and guards against potential legal issues, reinforcing the integrity of your project and acknowledging the contributions of the broader coding community.

Rule 7: Link to External References

When your code aligns with a specific standard, it’s paramount to explicitly mention this in a comment and provide a link to the relevant documentation. This not only serves as a helpful reference point for developers seeking to understand the rationale behind the code but also fosters transparency and adherence to established conventions. Incorporating these comments and links, you contribute to a well-documented codebase, promoting clarity, consistency, and facilitating collaboration among team members who may need to delve deeper into the specifications or standards guiding your implementation.

Rule 8: Comment Bug Fixes

When resolving a bug, go the extra mile by leaving a meaningful breadcrumb for future developers to follow: a concise comment, perhaps linking to an associated issue number or providing insight into the bug’s behavior, can prove invaluable. This thoughtful annotation not only aids in understanding the historical context of the bug fix but also guides developers who may encounter similar issues in the future.
Leaving behind this trail of information, you contribute to a more navigable and comprehensible codebase, empowering your team to troubleshoot efficiently and fostering a culture of collaborative problem-solving.

Rule 9: Mark Incomplete Code

In certain situations, you may find it necessary to commit code despite known limitations. When doing so, employ a standardized TODO format to explicitly highlight these constraints (@todo, @optimize). Clearly articulate any associated technical debt and consider linking to an issue tracker for comprehensive documentation. This practice not only serves as a transparent acknowledgment of existing limitations but also provides a clear pathway for future improvements. Incorporating this disciplined approach, you contribute to a more informed and proactive development environment, ensuring that known constraints are well-documented and can be systematically addressed in the ongoing evolution of the codebase.

Rule 9 and half: But.. avoid tags like @fixme: as it generally implies broken or faulty code. It is essential to refrain from committing broken code to the repository in the first place, prioritizing the delivery of functional and reliable code. @hack: as it generally Indicates that a particular part of the code is a temporary solution or workaround and needs further improvement. Prioritize the delivery of reliable code.

Conclusion

Comments should be viewed as companions to well-crafted code, not as remedies for suboptimal implementations. While comments can enhance understanding, relying on them to compensate for poorly written code only introduces confusion. A poorly executed comment might even obscure the code’s intent rather than clarify it.

Therefore, it’s crucial to bear in mind these guiding principles: aim for code clarity and conciseness first, ensuring that the code speaks for itself. When comments are warranted, focus on providing meaningful insights into the why, not just the what. Strive for clarity and brevity, avoiding verbosity that could potentially obscure the code’s essence.

Adhering to these guidelines, you foster a codebase that is not only maintainable but also comprehensible, promoting a collaborative and efficient development process.

Remember to clap, follow and share this post for maximum impact.

Your support means the world to me and can make a real difference in reaching people who would enjoy reading this story.

As I conclude, I want to express my gratitude for your valuable time. Thank you and have a wonderful day!

--

--

Giulio Rusciano

20+ yrs in technology leadership, design, development & entrepreneurship, I'm a creative technologist who blends design & tech to bring innovative ideas to life