Are Comments Good or Bad?!

If you look up “Tips to comment code” in google you will find 2 types of answers with 2 different philosophies

The first type of answer will say don’t use comments as it makes the entire source code look dirty and cluttered and the right way to write source code is to just make it readable by using good variable names and proper syntax. It is the duty of the reader to be proficient enough to make sense out of it. Only the “traps” in the source code need to be commented out.

The second type of answer will say comments are everything. Nobody will be able to remember the entire logic behind a piece of code after a year since they wrote it so it’s a good idea to write it down.

There is truth behind each of these philosophies. But they are both a bit extreme in the sense that one philosophy asks us, developers, to comment out everything possible and the other says comments are forbidden! As with many things with life the key is balance while using comments. So to answer the question

Are comments useful or not? Comments are useful if they are done in a proper manner.

Let’s discuss more on what the proper manner is in this article.

Need for comments

Comments are part of any programming language. In C we use “//” for single-line comments and “/**/” for multi-line comments. The syntax may vary, but take any programming language, you will find a way to enter comments in your source code. The programming languages that we are using today are developed years or possibly decades ago by the best minds in our field of computer science and programming. So what could have possibly gone through their minds while introducing these syntaxes into the programming language?

The answer is, they felt that comments are necessary.  But why?

The source code is meant for the compiler to understand and not for humans. Yes, the programmer who wrote it obviously knew what he was doing, but the logic of the inner mechanisms of the code came from his/her brain and not everyone’s brains work the same way. There are several paths you can take that can lead to the same result. Some are more optimized for RAM usage while others are more optimized for code size while others are a tradeoff between them.  There is another category that is not optimized at all, but just a roundabout way of doing something simple. I hope you are not stuck with some legacy code of this category..!!

The usefulness of comments for the code maintainer

Say you just joined a company and you are asked to work on a legacy project written by a developer who no longer works there. I bet you will find it easier to reimplement the entire project than to make sense of it using the source code with zero comments.

Let’s take another simple example. Let’s say you are using an open-source third party API provided by some organization. If you have any coding experience I bet you might have gone through some examples from some libraries. Whenever you find a function name with some ambiguous meaning, the first thing you will do is to go to the declaration of that function and read up the comments you can find above the function name. If you are like me, I guess you found it valuable and agree with me when I say that comments are useful. Comments make the experience of using code written by someone else a little less painful to understand and use.

The usefulness of comments for the developer who wrote it

Human memory is good at storing only the big picture, but it forgets the details. It is very common for source code to have a life of more than a few years before it becomes obsolete. Us developers usually move on from one project to the next as part of our job and come back to old projects if the sales and support team comes to us needing some bug fixing or some feature addition. The future “you” will surely appreciate it if there are some comments documenting the implementation. Some of the most frustrating things I ever did involve trying to decrypt my own code and trying to make sense out of it! So try not to be lazy and spend a few more minutes and comment out your source code!!

Comments will also help you to find weak points in your code. While writing the comments if you find that you can’t write a simple one-line description of a function you wrote, then it is a good opportunity to refactor the function into 2 or more simpler ones so that each function has a specific functionality.

Now that we have established that comments are useful, next let’s see when to use them and when to avoid them.

Classification of Comments

According to the book Code Complete (link to Amazon), comments can be divided into 6 categories

1. Repetition of the code in English

E.g. int x = 10; // set the value of the variable x to 10

2. Explanation comments

In this category, the code itself is very complicated and the comments help in decrypting it

E.g.

x = y + z; // variable x denotes the sum, y and z are the numbers being summed

Here instead it code could have been made better just by using better variable names as

Sum = number1 + number2;

3. Marker comments

 These include the  “FIXME“s and “TODO“s that we normally find in the codes. These don’t belong here, they belong in the feature and bug tracking tools.

4. Summary comments

This type of comment abstracts several lines of code into one or two lines. These are very useful especially for the interfaces so that the user of our code can understand what a particular interface function does.

5. Intent or Problem Statement comments

They describe the problem being solved by a block of code so that the reader can understand why that particular piece of code is written in the first place.

6. Unrelated comments

These include comments that are not related to the code itself. It can be about architecture, copyright notices, the license of use, references, etc. These are unavoidable and hence have its place in the comments.

You can read more about these categories in the Comments chapter in the book Code-complete (link to Amazon)

Levels of Comments

Based on the amount of code they explain, the comments can be classified into the following categories

  1. Line comments: Explain a single line of code
  2. Block comments: Explain a code block like a for loop or an if-else statement or a set of statements that implements a logic
  3. Function comments: Explain the logic implemented in a function
  4. File comments: Explain the file’s place in the program
  5. Program comments: Explain what the program does

Let’s briefly have a look at each of them in a little more detail.

1. Line comments

Try to avoid line comments. The only place these are useful is when you are describing a variable in its declaration line. Example use cases include

  • explaining the bit fields of a flag variable.
  • Explaining the units of a variable if it can’t be expressed in a variable name
  • Explaining the possible working range of values a variable can take.

Single lines of code should use proper variable names to avoid the need for comments.

2. Block comments

Block comments are useful to describe the intent of the code, in other words, it should describe the problem it is trying to solve.

For example

  • if you are doing a for loop, explain why it is needed in the first place, it is expected from the programmer to know what a for loop does, otherwise, he/she is in the wrong profession!
  • The same goes for if/else or switch statements for decision making. Explain why this decision making is needed and what the outcomes will look like, not how its getting done.

3. Function comments

  • Function comments are useful to summarize a function in 1 or 2 lines. If you can’t summarize a function in a concise manner then it’s a good idea to refactor and divide it into 2 or more functions.
  • Also, it’s a good idea to comment on the parameters to the function so that the reader can understand what each parameter refers to. Also, make sure that the global variables used in a function are documented.
  • Other than that, it is useful to document the limitations of a routine like the accuracy of results, the default behavior in case of parameter errors, etc.

 4. File and Program comments

These are useful in explaining the Software architecture decisions made. (If you wish to learn more about software architecture is, I am planning to write one in the near future, I will update the link here once it’s done). Also, this is the place to put in those legal notices and author information.

The above 5 categories can be combined to give us a structure similar to a book, with details about both high-level data (like preface and table of contents) and low-level data (like individual chapters) so that the entire source code becomes easy to navigate and understand.

Simple rules on when to use and avoid comments

  1.  Explain why you are doing something and not what you are doing and especially not how you are doing things
  2. Comments must be concise
  3. Comments should abstract the code and not repeat it
  1. Put the warnings and possible traps in comments. If something looks super obviously wrong but it is actually needed in the source code then comments are a good idea there.
  2. Avoid TODOs and FIXMEs in the comments, they belong in the bug and feature tracking tools
  3. Make every comment count, in other words, avoid commenting out parts that can be rewritten.

Along with the above rules just remember that inaccurate comments are worse than having no comments. So as you update the code, make it a rule to update the comments too.

Style/Syntax for using comments

Sadly there is no written rule/standard for implementing comments in the source code.  Each organization has its own rules and some even leave it to the developers to choose a style for comments. You can see the artistic side of the developer here with lots of *****,  #####, etc. But these styles are hard to maintain and there is a good chance that programmers will be reluctant to update a cool looking comment like this because of the added time it takes to align the “+” symbols

/*
+----------------------------------------------------+
+-----------Some comments----------------------------+
+----------------------------------------------------+
*/

Hence it’s a good idea to avoid them if possible and use something simple like this instead

 // Some comments

Since there is no official rule for comment syntaxes, I personally use the syntax provided by a tool named Doxygen for implementing comments in my code. This is a free tool and it can be downloaded through this link http://www.doxygen.nl/

All we need to is to adopt the commenting syntax provided by them and we can run their tool to generate some cool looking HTML documentation for our comments!

The best part is, it will take no longer than a couple of hours to get started with this tool. 

Let me give you a short 10 min demo of how to use Doxygen.

Short Demo of Doxygen Tool

Let’s look at a simple program which calculates the perimeter and area of a circle given the radius.

#include<stdio.h>

/// Mathematical constant PI.
#define PI 3.1415

/// Calculates the Area of the circle.
/// @brief Formula: Area = PI*r^2
/// @param[in] radius
/// @param[out] area
float calculate_area(float radius)
{
    float area;
    area = PI * radius * radius;
    return area;
}

/// Calculates the Perimeter of the circle.
/// @brief Formula: Perimeter = 2*PI*r
/// @param[in] radius
/// @param[out] perimeter
float calculate_perimeter(float radius)
{
    float perimeter;
    perimeter = 2 * PI * radius;
    return perimeter;
}

/// Main entry point of the program.
int main()
{
    float radius, area, perimeter;
    printf("Please enter the radius of the circle in meters: ");
    scanf("%f", &amp;radius);
    area = calculate_area(radius);
    perimeter = calculate_perimeter(radius);
    printf("Area = %.2f sq.m \n", area);
    printf("perimeter = %.2f m\n", perimeter);
    return 0;
}

Have a look at the comments.

The lines starting with 3 slashes (///) are a marker for the Doxygen program to process those lines while it produces the HTML output. Have a look at the image below.

All it took was 1hour of learning and a few clicks to generate this documentation..!!

Let’s take a look at the markers used in the code and their meanings

@param[in]: Input parameter to a function

@param[out]: Output parameter to a function

@brief: a brief explanation of the function

These are translated into the documentation like in the image below.

Thus we can accomplish 2 tasks in one go, comment on the source code and make the documentation to go with it.

If you need more then there is always Youtube and the official documentation..!

I am planning to write one more article on how to effectively comment on embedded source code. So stay tuned for that one! I will update the link here once it’s done.

I hope you enjoyed reading this article. Feel free to share it with your friends and colleagues!

If you have any questions or suggestions you can also email us or contact us through this link!

EI

We’re passionate about inventing embedded devices and we hope you are too! This blog deals with a wide variety of topics from C programming to IOT to networking certifications and more. Hope you enjoy your time spent here and hope you get some value out of our blog!

You may also like...