Your Good and Bad Friend: Comments in Programming

Soner Yıldırım
5 min readMay 20

How to and not to comment.

Photo by Joanna Kosinska on Unsplash

Comments are natural language text embedded in code that are meant for human understanding, not for computer execution. Here is a simple example:

# Calculate BMI: weight (kg) / [height (m)]²
bmi = weight_in_kg / (height_in_meters ** 2)

Comments in programming are used for a variety of purposes such as a “note to self” to document specific implementation choices or to highlight areas that need review in the future. Comments are also important in collaborative settings where many developers work on the same project. They help developers understand the purpose of a piece of code, serving as a way of communication among developers. They can also help clarify the functionality of specific parts of the code or explain the purpose of a given function or routine.

Although comments can be highly useful and necessary in some cases, they can sometimes do more harm than good if not used properly. In this article, we will talk about how to make the best out of comments in programming as well as how not to use them.

Bad comments

There are a few reasons why a comment can be considered bad. For instance, explaining what a function does through a comment when the function’s name should convey the same information is redundant.

In the following example, even if you are unfamiliar with the calculation of moving average, you can understand what exactly the function does so comments are redundant in this case.

def moving_average(lst, n):
Calculate moving average over a given list with window size n.
ret = np.cumsum(lst, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n

It is also not a good practice to log changes or keep commented-out code in the codebase. Since almost all projects are managed version control systems like Git, this practice is unnecessary and clutters the code.

Here is an example that illustrates this case:

def calculate_area(radius):
# Changed from 3.14 to math.pi for more accurate results - 2022/09/15
# return 3.14 * radius * radius
return math.pi * radius * radius
Soner Yıldırım

Data Scientist | Top 10 Writer in AI and Data Science | |