8 Types Of Source Code Comments

8 Types Of Source Code Comments

Having worked in a couple of multinational software companies as well as startups, I feel I have seen or at least heard about almost every type of software comment there is, I will try to list them, and I am happy for you to reach out to me if there is a type you feel I have missed.

In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added to make the source code easier for humans to understand and are generally ignored by compilers and interpreters that is how they can be written in free-form text, They can be written in any language.

Types Of Comments In Software Repositories

1. Commented source code

These are the worst type of comments you can find in a source code repository. They normally exist because some developer was testing out a couple of ideas, one of them finally worked so the developer just checked in the modified files without removing the commented-out code. They can also exist because someone needed to remove a piece of logic and thought it would be a good idea to leave it commented in case they needed it back in the future. (Hey Fellows, THIS IS WHY WE HAVE VERSIONING SYSTEMS).

#for p in retrieved_products:
#  p.price = p.calculate_item_price() + get_tax_value(p)
#  p.mark_updated()

If it's commented out, then it may rot: when you suddenly decide that you need it again, you realize that it no longer compiles, or needs to be rewritten to make it fit with other things that have changed in the meantime. Commented-out code also adds useless clutter to the source files and makes them confusing to read.

These types of comments you have already seen whether you are working for a large company or making use of open source components. These types of legal comments will have copy and usage rights. these types of comments are required when you are working for a large organization. The open source community uses them heavily too sometimes to limit commercial use or usage of open source components in closed source software Example from GNU #NoticeInSourceFile

Example :

/* Copyright (C) 1883 Thomas Edison - All Rights Reserved
 * You may use, distribute and modify this code under the
 * Terms of the XYZ license, which unfortunately won't be
 * written for another century.
 *
 * You should have received a copy of the XYZ license with
 * this file. If not, please write to: or visit :
 */

3. Documentation Comments

Documentation comments are intended for anyone likely to consume your source code, but not likely to read through all of it it. If you are building a library or framework that other developers will use, you need some form of API documentation. The documentation comments can be used to generate readable standalone auto-generated documentation documents. Also Integrated Development Environments (IDEs) can parse these Doc comments to provide guidance and hints to developers while writing software.

For example, Javadoc is a document generator tool in Java programming language for generating standard documentation in HTML format. It generates API documentation. It parses the declarations ad documentation in a set of source files describing classes, methods, constructors, and fields.

Example Documentation Comments:

// import statements

/**
 * @author      Firstname Lastname <address @ example.com>
 * @version     1.6  (current version number of program)
 * @since       1.2  (the version of the package this class was first added to)
 */
public class Test {
    // class body
}

and

/**
 * Short one line description.                           (1)
 * <p>
 * Longer description. If there were any, it would be    (2)
 * here.
 * <p>
 * And even more explanations to follow in consecutive
 * paragraphs separated by HTML paragraph breaks.
 *
 * @param  variable Description text text text.          (3)
 * @return Description text text text.
 */
public int methodName (...) {
    // method body with a return statement
}

4. Clarification comments

Clarification comments are intended for anyone (including you in the future) who may need to revisit a piece of code to either refactor or extend your code. Almost always, a clarification comment is a code smell. It tells you that your code is too complex. You should remove clarification comments and simplify the code instead

“good code is self-documenting.”

Example of a bad comment

/*  
* Replaces braces with spaces  
* as braces cause problems during processing
* provided inputs and cause stasis.
*
*/ 
$str = str_replace(array("\{","\}")," ",$str);

Rather than decorating a confusing statement, you could have spent the time making the code itself more readable Maybe a function named, remove_curly_braces called from another function named sanitize_input?

There are also times when you see a redundant comment. If the code is already simple and obvious, there’s no need to add a comment.

# Builds a list of product IDs from the list of products
p_ids = [p.id for p in all_products]

There are still times when no matter what you do to the code itself, a clarification comment is still warranted. This usually happens when you need to add some context to a non-intuitive solution.

Example :

static struct page *__dma_alloc(struct device *dev, size_t size,
                dma_addr_t *handle, gfp_t gfp)
{
    struct page *page, *free, *end;
    int order;

    /* Following is a work-around (a.k.a. hack) to prevent pages
     * with __GFP_COMP being passed to split_page() which cannot
     * handle them.  The real problem is that this flag probably
     * should be 0 on AVR32 as it is not supported on this
     * platform--see CONFIG_HUGETLB_PAGE. */
    gfp &= ~(__GFP_COMP);

5. Informative comments

These are comments that provide information to parties that may not be familiar with something with a specific business use case

Example

# matches an Egyptian mobile numbers
pattern = re.compile('^(\+2[- ]?)?0\d{10}$')

Any member of the team can simply read the expression without understanding it if they are not familiar with regex.

6. TODO Comments

Most programmers put TODO comments in their code to track problems they see and ideas they have. Programmers use TODO comments because they’re convenient and allow you to stay in the code, reducing distractions.

Example:

// TODO: Keeping this single threaded won't scale +bug

7. Warning of consequences

Example

# Warning this test is going to take a while to run
def test_loading_a_massive_file():
    ....

These types of comments are a warning to fellow developers of the consequences. Without these types of warnings, if a program/test suite runs slowly, your fellow developer might waste his/her time finding the problem.

8. Mock Comments

There are times when — after a lot of effort — it turns out that the seemingly naive solution to a problem is the best. In those scenarios it is almost guaranteed that some other coder will come around thinking they are much smarter than you are and start messing with the code, only to discover that your way was the best all along. Sometimes even that other coder is your future self.

In those cases, it’s best to save everyone the time and embarrassment and leave a comment.

Examples from SO Question : What is the best comment in source code you have ever encountered :

// 
// Dear maintainer:
// 
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
// 
// total_hours_wasted_here = 42
//
// Magic. Do not touch.

The above examples are more about being funny than being helpful. You SHOULD leave a comment warning others not to pursue some seemingly obvious “better solution,” if you’ve already tried and rejected it. When you do, the comment should specify what solution you tried and why you decided against it.

Please let me know if you think there are other types of comments that I missed, I am happy to discuss them.