Comment Density

Ratio of number of comments to number of statements

Description

The metric specifies the ratio of comments to statements expressed as a percentage.

Based on HIS specifications:

  • Multi-line comments count as one comment.

    For instance, the following constitutes one comment:

    // This function implements
    // regular maintenance on an internal database

  • Comments that start with the source code line do not count as comments.

    For instance, this comment does not count as a comment for the metric but counts as a statement instead:

     remove(i); // Remove employee record
  • A statement typically ends with a semi-colon with some exceptions. Exceptions include semi-colons in for loops or structure field declarations.

    For instance, the initialization, condition and increment within parentheses in a for loop is counted as one statement. The following counts as one statement:

    for(i=0; i <100; i++)
    If you also declare the loop counter at initialization, it counts as two statements.

The recommended lower limit for this metric is 20. For better readability of your code, try to place at least one comment for every five statements.

To enforce limits on metrics:

Examples

expand all

    struct record {
    char name[40];
    long double salary;
    int isEmployed;
};

struct record dataBase[100];

struct record fetch(void);
void remove(int);

void maintenanceRoutines() {
// This function implements
// regular maintenance on an internal database
    int i;
    struct record tempRecord;

    for(i=0; i <100; i++) {
        tempRecord = fetch(); // This function fetches a record
        // from the database
        if(tempRecord.isEmployed == 0)
            remove(i);         // Remove employee record
        //from the database
    }
}

In this example, the comment density is 38. The calculation is done as follows:

CodeRunning Total of CommentsRunning Total of Statements
struct record {
    char name[40];
    long double salary;
    int isEmployed;
};

01
struct record dataBase[100];
struct record fetch(void);
void remove(int);
04
void maintenanceRoutines() {
04
// This function implements
// regular maintenance on an internal database
14
int i;
struct record tempRecord;
16
for(i=0; i <100; i++) {
16
 tempRecord = fetch(); // This function fetches a record
        // from the database
27
if(tempRecord.isEmployed == 0)
            remove(i);         // Remove employee record
        //from the database
  }
}
38

There are 3 comments and 8 statements. The comment density is 3/8*100 = 38.

Metric Information

Group: File
Acronym: COMF
HIS Metric: Yes