How to not write code comments
Code comments are intended to clarify the logic of a program, however if misused they do more harm than good
Code comments serve as valuable insights into the logic, functionality, and
intentions behind a piece of code. Well-crafted comments can enhance code
readability and facilitate collaboration among developers. However, there is a
dark side to code comments—their misuse or implementation of bad practices. In
this article, we will shed light on some of the common bad practices for code
comments that can lead to confusion, maintainability issues, and hinder the
development process. Let's dive in and explore these practices, so you can
avoid them in your own code.
/* following is outdated comment, but I didn't understand
* the specific meaning, so I won't remove it yet:
* latest multi has higher priority
* (previous may leak and they would be free'd in shutdown)
* code before:
* cat_queue_push_front(&CAT_CURL_G(multi_map), &context->node); */
RB_INSERT(cat_curl_multi_context_tree_s, &CAT_CURL_G(multi_tree), context);
Outdated and Irrelevant Comments
One of the most significant issues with code comments is their tendency to
become outdated over time. Developers often overlook updating comments when
they modify or refactor code. Outdated comments can mislead other developers
and lead to confusion. Similarly, comments that are irrelevant or do not
provide any useful information add clutter to the codebase, making it harder
to understand the code's purpose and functionality.
# Calculate the sum of two numbers
def add_numbers(a, b):
# TODO: Implement a more efficient algorithm here
return a + b
Best Practice: Regularly review and update comments along with code
changes. Remove or revise comments that no longer serve a purpose.
Redundant and Repetitive Comments
Sometimes, developers fall into the trap of adding redundant or repetitive
comments. For example, commenting on every single line of code, stating the
obvious, or duplicating information that can be easily understood from the
code itself. Redundant comments create noise and increase the cognitive load
for readers, diminishing the value of comments as a communication tool.
// This is the start of the calculateTotalCost() method
public double calculateTotalCost(List<Product> products) {
// Loop through the products list
double totalCost = 0.0;
for (Product product : products) {
// Get the price of each product
double price = product.getPrice();
// Add the price to the total cost
totalCost += price;
}
// Return the total cost
return totalCost;
}
Best Practice: Focus on providing insights and explanations that cannot
be inferred from the code alone. Avoid restating what is already clear from
the code itself.
Incomprehensible or Unclear Comments
Clear and concise communication is vital when writing code comments.
Unfortunately, some developers use complex jargon, ambiguous language, or fail
to articulate their thoughts clearly. Incomprehensible comments can confuse
other developers, defeating the purpose of comments as explanatory aids.
Unclear comments can also mislead or cause misunderstandings.
# Function to process the data
def proc(dat):
# Loop through the items
for i in dat:
# Do the thing
res = do_thing(i)
# Process the result
process(res)
Best Practice: Use simple and precise language in your comments. Aim
for clarity and avoid technical jargon that might not be universally
understood. Be mindful of the target audience reading your code.
Commenting Obvious Code
Commenting obvious code is another common pitfall. It refers to explaining
straightforward or self-explanatory code that does not require additional
comments. This practice clutters the codebase and increases maintenance
effort, as developers must update comments unnecessarily alongside code
changes.
// This is a variable declaration
int x = 5;
// This is a loop that iterates through an array
for (int i = 0; i < array.length; i++) {
// This is an if statement
if (array[i] > x) {
// This is a print statement
System.out.println("Value is greater than x");
}
}
Best Practice: Reserve comments for explaining complex logic,
algorithmic choices, potential caveats, or any non-obvious aspects of the
code. Trust that well-written code can speak for itself.
Lack of Contextual Information
Code comments should not only explain how the code works but also provide
crucial contextual information. Unfortunately, some developers focus solely on
the technical implementation details while neglecting to explain the why or
the big picture. Without contextual information, it becomes challenging for
other developers (including future maintainers) to grasp the code's intention
or its role within the broader system.
# Validate input
def validate_input(input_data):
# Check if the input is valid
if input_data is not None and len(input_data) > 0:
# Perform validation logic
return True
else:
return False
Best Practice: Include high-level explanations, references to
specifications or requirements, and any relevant background information that
can help readers understand the purpose and significance of the code.
Conclusion
While code comments can be valuable tools for enhancing code readability and
understanding, the misuse of comments can lead to confusion, maintainability
issues, and hinder the development process. By avoiding bad practices such as
outdated or irrelevant comments, redundancy, unclear explanations, commenting
obvious code, and omitting contextual information, developers can harness the
true potential of code comments. Strive for clarity, conciseness, and
relevance in your comments to ensure they serve as a helpful aid to fellow
developers and future maintainers.