A Comprehensive Guide To Code Commenting: Best Practices

by Noah Jackson

Developing software is difficult in many ways. When faced with working on someone else’s code that does not employ comments, not only is the process …

Developing software is difficult in many ways. When faced with working on someone else’s code that does not employ comments, not only is the process of programming made more difficult, but it is also made exponentially more complex.

Imagine you’re given all of the ingredients for making bread but no recipe. You may be aware that the dry components go together, but you may not be aware of the quantities of each. The same is true for code commenting, which might serve as a type of summary of how a programmer utilized a function or how something was adjusted to address a specific difficulty.

Comments in code are essential for efficient and successful programming. “It’s harder to understand code than it is to write it,” remarked Joel Spolsky, co-founder of StackOverflow. What makes that so? Poor commenting is one of the reasons. When developers don’t comment on their code, it’s very hard to figure out what’s going on. That miasma of code, however, is much easier to grasp with a firm road map of comments. So, what are the dos and don’ts of code commenting for those wishing to assist their engineers better their work? Let’s take a closer look.

Why bother writing code comments?

Why bother writing code comments?

Most of the time, you aren’t the only one working on the same project or codebase. That means that other people will have to read your code and comprehend it. That also applies to any code comments you leave behind. Devs frequently leave short and lazy comments with little context, putting other developers in the dark about what they’re trying to express. It’s a terrible habit that merely adds to the uncertainty rather than clearing it out.

So, yes, you should bother providing relevant code comments to assist other engineers. A code remark that outlines the function, the logic behind it, and its input and output can help other developers learn faster. This information is very useful for young engineers who are learning the code.

Code comments, on the other hand, raise the question of whether they should be written. There is a sizable number of developers that oppose making code comments. The rationale for this is that the code should be self-explanatory. It’s awful code if another developer can’t comprehend the objective of your code just by looking at it. This may be true, but consider the minimal work required for code commenting and the possible benefits it provides. Code comments are useful for speeding up the onboarding process for any developer, especially younger developers.

Now, let’s look at the many forms of code comments.

Different Types of Code Comments

Different Types of Code Comments

Documentation comments:

The primary goal of these comments is to rapidly clarify the function of a file or component. Instead of going through the complete code of a component to figure out what it does, you can insert a code remark at the start of your ‘index’ file to describe what the component does.

This style of code commenting, however, can make your code lengthy. These sorts of architectural remarks should be kept in your internal documentation, where you can update and debate your project’s architecture in a single spot. However, it does provide value to Open Source projects to guide others who wish to contribute to the project.

Function comments: 

Function comments are the most helpful sort of remark and can be created automatically in a variety of languages. They define the function’s purpose, the parameters it accepts, and the output it produces. Because developers who use your code will not interact with private functions, it is typically sufficient to specify solely public functions.

/**

 * @desc Creates a welcome message

 */

function sayHello(name) {

    return `Hello ${name}`;

}

Logic comments:

Logic comments are comments that are placed into functions to help simplify complicated code logic. It’s an obvious code smell or technical debt suggesting that your code is way too sophisticated, as you could have expected.

Furthermore, logic comments can give excessive information. The degree of detail will add to the confusion and reduce the readability of your code. Here’s an example of an overly detailed code comment.

let date = new Date(); // store today’s date to calculate the elapsed time

Code Comments: Do’s and Don’ts

Code Comments: Do’s

Do Use Comments as a Method to Communicate

One of the most important things you need to make clear to your programmers is the importance of using comments to express their intentions and actions to other programmers. When one programmer inserts well-written comments in their code, they are communicating with all of their colleagues about the status of their work.

Do Write Comments With The Reader in Mind

Similarly, your engineers should keep in mind that comments should be written with other people in mind. This tool isn’t just for leaving remarks regarding their work; it’s also for assisting others in deciphering what they’ve done.

One of the primary functions of comments is to assist other programmers in understanding what is going on within the code. This implies that your developers must write in such a way that any developer can open their work and comprehend what’s going on.

Do Work to Eliminate Confusion

Code commenting should be used to clear up any ambiguities in the code. It’s not about bragging about their work, but about making the process of cooperation and understanding easier. The primary purpose of code commenting should be to make their work transparent and evident. This implies that your developer’s comments should be extremely clear and succinct as well (and not add even more confusion to the mix).

Do Provide Links to The Original Source of Copied Code

When your developers copy code from other places, they should always include links to the original sources. Why? Because Whoever follows in their footsteps may need to know why they used that piece of code and what its original aim was, and may even need to contact the developer of the copied code.

Do Add Comments When Fixing Bugs

Code comments should be used not just for original (or copied) code, but also when your developers repair errors. These remarks should clarify what they did to resolve the problem and why it was required. Again, your engineers should avoid providing long how-tos in the comments and instead be concise and efficient in their terminology.

Do Use Code Annotations or Tags

Code annotations and tags should be used by your developers to assist keep things succinct. @desc, for example, is a description, @param is a description of arguments, @returns is a description of the returned output, and @throws is a description of probable error types. Most developers should be familiar with such annotations and tags. If not, make sure they learn them.

Do Write Comments While Writing Your Code

Instead of adding comments after the code is finished, have your engineers write them as they go. This can save you a lot of trouble. For starters, it will keep a developer from forgetting why they wrote anything. Second, if something occurs to a developer in the middle of a project, the comments are already there, so someone else may easily start up where they left off.

Code Comments: Don’ts

Don’t Comment On Everything

It’s also critical that your engineers realize that they shouldn’t remark on everything. Developers should refrain from commenting on the obvious. This is a common error made by inexperienced programmers who believe they must record everything they produce along the way.

To assist with this, have your developers assess whether what they’re producing adheres to commonly established norms and syntaxes, which implies it probably doesn’t require a remark.

Don’t Use Comments To Replace Documentation

Documentation and code comments are not the same thing. You don’t want developers to use comments as documentation since the code will become far too lengthy (and unclear), resulting in more effort. This occurs frequently because developers despise producing documentation.

The purpose of code comments is to clarify certain functions and techniques, not to describe how something works in detail. If your developers are including unnecessary information in their code comments, you’d better put a stop to it before it becomes a problem.

Don’t Refer to Someone Else’s Comments in Your Comments

If your developers refer to other comments (or even other papers), they are adding to the workload of other developers. Consider the following: A developer inserts a remark into the code that references another comment. This implies that any developer who follows that person will have to go through the code to discover the referred-to comment. That’s a lot of labor.

Rather than referring to another remark, your developer should state what they need to say (and do so efficiently). The objective should be to delegate less work to others rather than more.

Code Comments: 5 Best Practices

Code Comments: 5 Best Practices

Here’s a list of four best practices for code commenting.

Make use of code annotations or tags

Many programming languages set code commenting standards, for example, Java uses Javadoc, and JavaScript employs the JSDoc code commenting system, which is supported by a wide range of documentation creation tools.

For functions, you should include the following code tags:

  • @desc – Write down a description for your function.
  • @param – Describe all input parameters that 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 is 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

}

Write down why you are doing something

Many programmers use comments to describe what their code does. This is not necessarily wrong. However, don’t forget to explain why you built a certain function or component. This information is referred to as context. The context is critical for developers to have a better understanding of the design decisions that went into a function or component. When other developers wish to make modifications to your function or component, this context is critical.

Code comments that use the function name in the function description are common. As you can expect, such a remark adds nothing to the conversation. Context refers to the addition of information that cannot be derived from the function name or its input variables. A terrible example of code commenting without context is shown below.

/**

 * Sets the label property of a new form.

 *

 * @param label text for label of form

 */

function setFormLabel(label) {

    // logic

}

Don’t refer to other documents or comments

Referring to additional code comments or internal papers that clarify a function or component is not a good idea. If a developer wants to quickly review code to have a better understanding, the code comments must be clear.

You don’t want to waste time looking for more code comments or reading lengthy docs. If you believe you need to add a document to describe the objective of a code, this is a sign of bad code.

/**

 * Sets the label property of a new form.

 *

 * @see {@link https://myinternaldocument.com}

 */

function setFormLabel(label) {

    // logic

}

Write comments while writing code

Creating comments while writing code may seem apparent, yet many developers break this guideline. You should write comments while you code because you may forget some of the reasoning behind what you wrote, resulting in lower-quality code comments. This is especially true if you work on a single pull request for several days. When you finish a function or module, it’s great to leave comments right away.

Create codebase issues and link them to code

Engineers spend the most of their time in the editor’s chair. If you want to enhance your communication skills, start where you spend the most of your time: in the editor’s chair. With the growth of extensions, developers may now stay within their development environment without having to transition between multiple tools.

The JetBrains and Stepsize VSCode addons will assist you in creating codebase problems, comments, and to-dos. This will give your team a better understanding of all codebase issues and will be able to fix them more regularly. 

Final words

Take the time to add meaningful code comments if you care about code quality. It takes some practice, but won’t take long to master. The important thing to remember is to include context in your code comments. Describe the reasoning behind the code you’ve written, not just the obvious facts.

Developers don’t require the ‘what’ since they can better grasp the code by reading your code, input parameters, and output. Always keep your code comments as brief as possible since you don’t want to waste time creating code comments rather than writing code.

If your company doesn’t have the expertise to execute your software development project in-house, it’s best to find a service provider to help you. 

CMC Global is among the top three IT outsourcing services providers in Vietnam. We operate a large certified team of developers, providing a wide variety of stacks, to help you build your web application in the most cost-effective way and in the least amount of time. 

For further information, fill out the form below, and our technical team will get in touch shortly to advise!