Comments in code: best practices and 4 mistakes to avoid
What are code comments?
In computer programming, comments in code are used to include information on portions of source code in a project. Code comments are intended to make the related code easier to understand by providing additional context or explanation.
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.
· added to source code using a special syntax, which varies depending on the programming language in question. In many languages, comments are denoted by a specific character or sequence of characters (e.g. `//` or #).
In the dev community, code comments are controversial. Some disown the practice altogether, claiming comments actually make code worse, while others maintain it as a necessary element of professional programming.
Regardless of which bucket you fall in, understanding code comments best practices will serve you well in a career as a professional software developer and will make you a more appealing project collaborator.
Code comments best practices
A good best practice to follow when writing comments in code is to describe the why, not the what. In general, good code should be self-explanatory in how it works, at least in isolation. Explain the reasoning behind the code, not just what the code is doing. This can help others understand the intent of the code.
When adding a code comment, consider following these code comments best practices:
- Make comments meaningful. Comments should not duplicate the code. It would be silly if a code’s corresponding comment just copied the code itself. Comments should add useful context, information, explanation, etc. Avoid writing comments that simply repeat the code or state the obvious.
- Comment on your classes, methods, and functions. Include brief descriptions of classes, methods, and functions so others can understand the purpose of these items in the codebase. These are great cases for using comments. They explain the class or function in isolation, and are found where they are needed - next to the code they are explaining.
- Use clear and concise language. Comments should be written in clear and concise language. Avoid using jargon, slang, or complex vocabulary. Avoid personal notes, remarks, or jokes. Generally, a good rule of thumb when it comes to code comments is: less is more.
- Use correct grammar and punctuation. This increases the legibility and value of your code comment.
- Be consistent with your commenting style. Establish a commenting style for your code comments with you and your team and be consistent with it. In most cases, code is divided into levels like chunks, functions, modules, libraries, etc. It’s best to develop a specific commenting style for each level and stay consistent.
- Include reference links when relevant. If you use code that you found online or unidiomatic code, include a link reference to the source in a code comment to help future readers. Similarly, if there is an external source that provides helpful context for your code, include a link in a comment.
- Write comments at the same time you’re writing the code. Depending on the complexity of the code in question, there may be weeks between when you start and finish your task at hand, and in that time, you can forget why you made some of the decisions you did when writing the code. Some developers actually suggest writing your comments before you write the code and letting it guide you.
By following these code comments best practices, you can help make your comments more readable and understandable for everyone working on the project.
Things to avoid when writing code comments
One of the most important things to keep in mind concerning code comments: incorrect information is worse than no information at all. Comments should dispel confusion, not cause it.
You should understand the limitations of comments. Trying to explain flows across multiple source files or repositories; using comments is liable to be more confusing than helpful. There are better ways to explain these flows, as we will describe later.
Similarly, a good comment doesn’t excuse unclear code. If you can’t write a clear comment to explain a code chunk in isolation, there may be a problem with the code.
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. Use tools that are adept for that job instead.
- Don’t leave “To-Do” comments. Use work management systems for this. If you’re pushing a TODO, you should be creating an issue instead. Otherwise, you’re just generating technical debt.
- Don’t write comments in the wrong place. Add your code comments in a logical location within the code, and keep your practice consistent. This makes it easier to find comments when you need them.
- Don’t comment out code. Instead of commenting out code, it’s better to use a version control system, such as Git, to track your code changes.
- Don't over-comment. Too many comments can make code harder to read and understand. Only add comments when necessary, not to every line of code. Avoid redundant comments.
Alternative uses for code comments
Use comments to mark incomplete implementations. While it may be tempting to hide deficiencies in your code, it can be extremely helpful to add this information in your code comments.
Code comments FAQs
Should I add a comment when fixing bugs?
In most cases - yes. Comments should be added when fixing bugs and otherwise modifying existing code. Not only do these comments help future readers understand the code in its new state, they help determine whether the code is still needed in the future and how to test it. They will make the next developer who touches this part of the code aware of pitfalls that have resulted in bugs in the past. It’s also recommended to include your name and the date the bug was fixed.
Can I edit another person’s code comment?
Yes, but follow the golden rule of “do no harm.” If a comment is incorrect or outdated, update it, or remove it if you don’t have enough information to correct it. Remember: incorrect information is worse than none at all.
Should I use comments to explain flows, complex logic, recurring patterns, etc?
Generally, no. For code that does require a more detailed explanation to explain flows, recurring patterns, or complex logic, high-level code documentation and walkthrough documentation should be implemented as a second step to a code comment.
Does good code need comments?
Yes, good code still needs comments.
There are some who believe that comments are used to excuse poorly-written or unclear code. While it’s true that well-written code is clearly understood and exhibits some “self-documenting” characteristics, that doesn’t mean that good code shouldn’t also include good comments.
Can good comments fix bad code?
No, good comments cannot fix bad code. But they can help.
You might find yourself in a situation where the code—and even the comments—are poorly written. Consider rewriting or refactoring code in these situations. If that’s too risky, at least rewrite the comments. If there’s just too much going on and inline comments won’t cut it, consider writing documentation outside of the code specific to the code in question.
Code comments & documentation
Code comments explain specific lines of code in and of itself, within the relatively isolated context of precisely where it’s written. As long as we remember that this is their point, we can see that well-written and well-placed code comments can do their job quite well. Because of their very nature, code comments can’t provide the bigger picture. For example: what does this line of code do as part of a complex architecture or within the broader logical flow?
Teams should also have more detailed and comprehensive documentation that describes the overall architecture, design, and functionalities of the software. This can be done through walkthrough documentation, as well as external documentation, such as technical documentation, user guides, or README files.
There are several reasons why it’s important to have comprehensive documentation for a software project, even if quality code comments are present.
- Clarity and understanding. Documentation can provide a clear and complete understanding of the architecture, design, and functionality of the software. This can be especially helpful for new developers joining a project and others not familiar with the codebase.
- Communication. Detailed documentation can help improve communication between different team members and departments, and between development teams and other stakeholders. It also helps communicate the requirements and objectives of a project.
- Maintenance and evolution. Documentation provides an understanding of design decisions that were made during the development of the software. This can help to maintain the software over time and make changes to the codebase without introducing new bugs.
- Compliance. Some software projects are subject to various legal, regulatory, or corporate compliance standards. Documentation can help demonstrate the software is in compliance with related standards.
- Knowledge transfer. Documentation can be used to transfer knowledge about the project to other people or teams. It can be especially useful if team members change or a company merges, allowing the new collaborators to understand and continue the project.
Using Swimm for better code comments & documentation
Even if you have the best code comments in the world, you still need high-level documentation and walkthrough documentation for your project. Likewise, if you have the most detailed documentation, you still need quality comments.
Swimm is designed to be the perfect bridge between code comments and documentation for development teams. Swimm allows teams to create walkthrough documentation - taking the reader on a guided tour of the codebase, while often using code snippets to explain points of interest on the map. As it moves from landmark to landmark, walkthrough documentation can point out recurring patterns, or describe interactions between different blocks of code that may reside quite far from each other or even multiple repositories. Using Swimm, developers can quickly add code snippets to a project’s documentation. This means that the textual descriptions within Swimm’s documents are available right inside your documentation simply by selecting a code snippet.
If you’re using one of the IDE plugins offered by Swimm, you can add a link to available documentation right inside your code. This makes it easy to find the information you need exactly when you need it, saving lots of time and mental energy.
With Swimm, all of your walkthrough documentation is saved directly to your repository as part of the codebase, giving you the ability to access it inline, exactly where and when you need it. Or, access it externally from your codebase in the Swimm app.
Because Swimm offers code-coupled documentation, you can find information quickly, ensure it includes important information about flows and patterns, and automatically detect outdated items to avoid abandoned or lost docs.
Get started by signing up for a demo with Swimm: onboarding is faster, development is consistently more efficient and productive, and your team members are happier.