comment code ratio
comment code ratio

What is a Better Comment/Code Ratio While Coding?

Comments are an important part of any Python code. A comment is a piece of text written inside Python code. It is not executed by the compiler or interpreter when the program is executed. Programmers often make use of comments in the code for various reasons and to improve the readability of the program. In this article, we will discuss what is a better comment/code ratio for any program. To answer how many comments to include in your code we will first discuss the need of including comments in our source code.

What Is the Need for Comments in a Python Code?

We should know that comments do not modify the functionality of a program. Python interpreter does not execute the comments. However, comments are essential to improve the readability and understanding of the source code. To decide what a good comment/code ratio is, we will first look at why the comments are needed in a code. The following are reasons that address the need of including comments in our source code.

Documentation of the Source Code

Source code documentation is an integral process for software maintenance and management. We often use comments for the documentation of the source code. Whenever a developer creates a Python library or a module, he or she also provides the documentation of source code. This documentation includes a detailed description of all the methods used in the source code. This description includes the specification of parameters, input values, and output values. Documentation can be done with both single-line comments as well as multi-line comments inside a function in Python as follows.

# This function performs the average of all numbers of the list
def list_avg(lst):
    """
    Parameter:
        lst: a list of numbers
    Returns:
        A floating point number
    """
    total = 0
    for num in lst:
        total += num
    avg = total/len(lst)
    return avg

Clarification of Code

Whenever we use a specific function or a statement in our Python code, it may be possible that it is difficult to understand its usage. Therefore, we use comments to specify the usage of that function or statement in our code. It clarifies why a part of the code is written at that particular place. It helps the reader to understand the code. Example,

# function to check whether a number is prime
def isprime(num):
    no_of_divisors = 0
    # this loop will check divisors of given number  
    for i in range(2, num):
        # if statement to check whether 'num' is divisible by i
        if num % i == 0:
            no_of_divisors += 1
    if no_of_divisors >= 2:
        return False
    else:
        return True

In the above example, the use of for loop and if statement inside the loop seems to be unclear. Therefore, we have specified comments to clarify the statements.

Specifying the Instructions

In some cases, there is a need to follow some instructions while executing our code. We use comments to specify those instructions so that a programmer could easily execute the code. In addition, there is the possibility of bugs and runtime errors in our code. The programmer who will be using this code must be aware of these problems. So, comments should be provided to specify the instructions which help in debugging the code.

Specifying the license or copyright and contracts

When we write a source code for any commercial purpose, it is conventional to specify certain details in the code. These details include the name of the author, the date and time at which the code was created. We specify the license or copyright-related details of the source code. If we are writing the source code for another firm, we should also specify the contract details.

These are Legal details and are necessary for other users and readers to know how they can handle the source code without any legal issues. These details are specified using Header comments in the source code. Header comments are the comments that we write at the start of the source code file.

Example,

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon July 19 20:15:03 2021

@author: piyush21
This code is for avidpython.com
"""

What Should a Comment in the Code Do?

To decide on the standard comment/code ratio, we should also look at the reasons why a comment is included in a code.

Explain Why a Statement Is Written

A comment should explain why a statement or expression is written in the code. However, we must know that we should not provide a comment or explanation for each statement. A comment should be provided only when a statement doesn’t seem to be obvious and it is difficult to understand its purpose. Excessive and unnecessary comments may make the code difficult to read and will reduce the readability of the code.

Let’s take an example,

# comment 1 - initializing a dictionary
mydict = {'name':'rahul', 'age': 19, 'marks': 92.88}
print('Initial dictionary:', mydict)

# comment 2 - simplyfying marks to nearest greatest integer value
mydict['simplified_marks'] = int(mydict['marks']) + 1

# comment 3 - deleting 'marks' key-value pair from dictionary
del mydict['marks']
print('Modified dictionary:', mydict)

Output:

Initial dictionary: {'name': 'rahul', 'age': 19, 'marks': 92.88}
Modified dictionary: {'name': 'rahul', 'age': 19, 'simplified_marks': 93}

In the above example, comment 1 and comment 3 are absolutely unnecessary as they are explaining the obvious statements. However, comment 2 is important as it explains a statement that may not be understood by a user. Here, it explains about simplification of marks.

Do Not Explain the Working of a Statement

Comment should not explain how a statement is working or performing an operation. Every statement or expression in a code is doing something. Therefore, it is not necessary to explain the working of each line of code. A reader or a programmer can understand how a statement is executed if he or she knows Python. There may be some cases one doesn’t understand a statement. In that case, a comment should be provided to explain the purpose of the statement instead of working of that statement. A programmer or reader can figure out working once the purpose or usage is clear.

In simpler words, we should write comments that answer why a statement is written but not how it is working.

Specify the Metadata of the Source Code File

Comments should specify the metadata of the source code file. This includes the information regarding the encoding of text and the version of the programming language used in the code. This also includes the author’s name, date-time of creation, date-time of modification (if any), and project URLs. Proper header comments should be provided to specify the metadata of the source code file.

Conclusion

In this article, we have read about the need for comments and the purpose of comments. Having read these details, we should understand that there is no standard comment/code ratio. We can use any number of comments as long as comments are serving their purpose. But we should keep in mind not to include redundant comments in the code and not comment about obvious parts of the source code. If we use comments in an efficient manner it improves the readability of code and makes it more understandable.

I hope you enjoyed reading this article. To know more about python programming, you can read this article on Command line arguments using sys.argv list in Python. You might also like this article on python indexing.

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply