27
4 Best Practices for Writing Meaningful Code Comments
In most cases, you aren’t the only person working on the same project or codebase. That means that other people get to read your code and have to understand it. That’s also true for the code comments you leave behind. Developers often write ‘quick and dirty’ comments without much context, leaving other developers clueless about what you’re trying to say. It’s a bad practice that creates only more confusion than clarifies things.
So, yes - you should be bothered with writing meaningful code comments to help other developers. A code comment that describes the function, the reasoning behind the function, and its input and output will speed up the learning process of other developers. Especially for junior developers, this information comes in handy when learning the code.
On the other hand, code comments lead us to the discussion whether we should write them? There’s a significant group of developers that advocate against writing code comments. The reason being that code should be self-explanatory. If another developer can’t understand the purpose of your code by looking at it, it’s bad code. This might be true, but think about the little effort code commenting requires and the potential benefits it returns.
Plus, code comments are valuable to boost the onboarding process for any developer.
Let’s take a look at the different types of code comments.
1. Documentation comments - The main purpose of these comments is to quickly clarify the purpose of a file or component. Instead of reading a component’s entire code to understand what it does, you can include a code comment at the top of your index
file to explain what the component does.
I’m not a big fan of this type of code commenting because they make your code very noisy. I think that these types of architecture comments should live within your internal documentation where you can maintain and discuss your project’s architecture in a centralised location. Yet, for Open Source projects, it does bring value to guide people who want to contribute to the project.
2. Function comments - Function comments are the most useful type of comments and can be automatically generated in many languages. They describe the purpose of the function, which parameters it accepts, and what output it generates. It’s often sufficient to describe only public functions because developers using your code won’t interact with private functions.
/**
* @desc Creates a welcome message
*/
function sayHello(name) {
return `Hello ${name}`;
}
3. Logic comments - Logic comments are comments within functions to clarify complex code paths. As you could have guessed, it’s an evident code smell or technical debt indicating that your code is far too complex.
On top of that, logic comments often provide too much detailed information. The level of detail will create more chaos and decrease the readability of your code. Here’s an example of a code comment that’s too detailed.
let date = new Date(); // store today's date to calculate the elapsed time
Here’s a list of four best practices for code commenting.
Many programming languages define standards for code commenting. Java uses Javadoc, while JavaScript uses the JSDoc code commenting system that’s supported by many documentation generation tools.
For functions, you should include the following code tags:
@desc - Write down a description for your function
@param
- Describe all input parameters the function accepts. Make sure to define the input types.
@returns - Describe the returned output. Make sure to define the output type.
@throws - Describe the error type the function can throw
@example - Include one or multiple examples that show the input and expected output
Here’s an example from the Lodash code for the chunk
function.
/**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @returns {Array} Returns the new array of chunks.
* @example
*
* chunk(['a', 'b', 'c', 'd'], 2)
* // => [['a', 'b'], ['c', 'd']]
*
* chunk(['a', 'b', 'c', 'd'], 3)
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size = 1) {
// logic
}
Many developers use a comment to describe what their code is doing. This is not necessarily wrong. However, don’t forget to include why you have created a particular function or component. This information is called context. The context is essential to give developers more insights into the design decisions behind a function or component. This context is crucial when other developers want to make changes against your function or component.
You often see code comments that use the function name in the function description. As you could have guessed, such a comment doesn’t add value. Context refers to adding information that you can’t extract from the function name or its input variables. Below you see a bad example of code commenting without context.
/**
* Sets the label property of a new form.
*
* @param label text for label of form
*/
function setFormLabel(label) {
// logic
}
Pro tip: try to use a free Stepsize VSCode extension to add code context for tech debt, refactoring, or TODOs.
It’s not a good idea to refer to other code comments or internal documents that clarify a function or component. If a developer wants to scan code to get a better understanding quickly, the code comments should be clear.
You don’t want to spend time searching for other code comments or reading extensive design documents. If you think you need to add a document to clarify a code’s purpose, it’s a red flag for bad code.
/**
* Sets the label property of a new form.
*
* @see {@link https://myinternaldocument.com}
*/
function setFormLabel(label) {
// logic
}
Writing comments while writing code might sound obvious, yet many developers cheat against this rule. I’ve been guilty of this myself. In some situations, I’ve completed my code before writing any code comments to submit my pull request for review.
You might forget part of the logic you wrote in this situation, leading to lower quality code comments. It’s especially true if you work multiple days on a single pull request. It’s best to write comments when you complete a function or module.
If you care about code quality, take time to write meaningful code comments. It takes some practice but can be quickly learned. The key concept to remember is adding context to your code comments. Describe the why behind the code you’ve created, not only the apparent information. Developers don’t need the ‘what’ because they can read your code, input parameters, and output to better understand the code.
Remember to keep your code comments as concise as possible. You don’t want to spend more time writing code comments than writing code.
This post was written by Michiel Mulders. Michiel is a passionate blockchain developer who loves writing technical content. Besides that, he loves learning about marketing, UX psychology, and entrepreneurship. When he’s not writing, he’s probably enjoying a Belgian beer!
Also published on: Managing Technical Debt.
27