Code Commenting: Common Mistakes and Their Solutions and Tools!
Code comments play a vital role in various aspects of code #development. They enhance the understanding of complex code, improve software #readability and #maintainability, simplify #debugging processes, and facilitate code reuse, among other benefits. However, one thing they can't achieve is magically transforming poorly written code into high-quality code. Hence, to increase their effectiveness, they must be written as valuable aids rather than becoming a burden.
his article explores common mistakes made while writing comments and offers practical solutions, along with #tools, to ensure that comments contribute positively to the #codebase.
The Absence of Code Comments:
Mistake: Omitting comments entirely from the code!
Solution: Whenever you write, edit, or delete code, remember to include a brief and concise comment describing the event.
Tools: Code Linters, #IDEs with commenting features like #VisualStudio, #Intellij, and AI tools like Github Copilot. Knowl can help you to generate comments #automatically so that your code is never without comments.
Code Example: (Language: #Python)
Mistake: No Comments.
def is_valid_ipv4(s):
parts = s.split(".")
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit():
return False
i = int(part)
if i < 0 or i > 255:
return False
return True
Solution: Code with Comments.
def is_valid_ipv4(s):
# Split the string by the dot character. An IP address eg.
# 123.212.141.156
parts = s.split(".")
# An IPv4 address should have exactly 4 segments
if len(parts) != 4:
return False
for part in parts:
# Ensure each segment is a number
if not part.isdigit():
return False
# Convert the segment to an integer
i = int(part)
# Ensure each segment is in the range 0 to 255
if i < 0 or i > 255:
return False
# If all checks pass, the string is a valid IPv4 address
return True
In this example:
The Complex Comments:
- Mistake: Writing overly complex comments that only the original coder can understand.
- Solution: Use clear and simple language in your comments. Explain your code as if you were explaining it to someone with no prior knowledge of the project.
Code Example: (Language: #Python)
Mistake: Complex Comments.
# This function employs a recursive algorithm to traverse the binary # tree in a depth-first manner.
# It employs the pre-order traversal approach, which involves #visiting the root, then recursively
# traversing the left and right subtrees. The base case checks for a # null node and terminates the recursion.
def traverse_binary_tree(node):
if node is not None:
visit_node(node)
traverse_binary_tree(node.left)
traverse_binary_tree(node.right)
Solution: Comments Explained in Simple Language.
# This function goes through a binary tree in a specific order: #root, left subtree, right subtree.
# It checks if the current node exists, visits it, then moves to the # left and right nodes recursively.
def traverse_binary_tree(node):
if node is not None:
visit_node(node)
traverse_binary_tree(node.left)
traverse_binary_tree(node.right)
The Outdated Comments:
- Mistake: Leaving outdated comments that no longer reflect the code's functionality.
- Solution: Regularly review and update comments to ensure they accurately reflect the code's current state and purpose.
- Tools: Static Code Analysers, #`Docusaurus, MkDocs can detect and flag the outdated comments. Knowl AI also helps ensure the comments are never out-of-date.
Code Example: (Language: #JavaScript)
class ShoppingCart {
constructor() {
this.items = [];
}
// Add an item to the shopping cart.
addItem(item) {
this.items.push(item);
}
}
Mistake: No Comment Updatation as the Code Evolves.
class ShoppingCart {
constructor() {
this.items = [];
}
// Add an item to the shopping cart -outdated comment
addItem(item) {
this.items.push(item);
this.updateTotalCost(item.price);
}
// Update the total cost of the shopping cart.
updateTotalCost(price) {
this.totalCost += price;
}
}
Solution: Update the Comments as the Code Evolves.
class ShoppingCart {
constructor() {
this.items = [];
this.totalCost = 0;
}
// Add an item to the shopping cart and update the total cost -
//updated comment
addItem(item) {
this.items.push(item);
this.updateTotalCost(item.price);
}
// Update the total cost of the shopping cart.
updateTotalCost(price) {
this.totalCost += price;
}
}
The Comments Overload:
- Mistake: Writing too many comments, making the code harder to read.
- Solution: Keep comments concise and relevant. Avoid commenting the obvious and focus on explaining complex or non-intuitive parts of the code.
- Tools: CLOC (Count Lines of Code) can give idea to identify if there's an excessive amount of comments in your codebase.
Code Example: (Language: #CSharp)
Mistake: Too Many Comments.
using System;
public class RandomNumberEvenOddCheck
{
public static void Main()
{
// This section generates a random number between 1 and 100.
// We use the Random class to achieve this.
Random random = new Random();
// Generate a random number between 1 and 100.
int randomNumber = random.Next(1, 101);
// Now, we print the random number to the console.
Console.WriteLine($"Random number: {randomNumber}");
// Here, we calculate the square of the random number by
//multiplying it with itself.
int square = randomNumber * randomNumber;
// We print the result to the console along with a
//descriptive message.
Console.WriteLine($"The square of the random number is
{square}.");
// Now, we check if the square is even or odd using a
//conditional statement.
if (square % 2 == 0)
{
// If it's even, we print this message.
Console.WriteLine("The square is even.");
}
else
{
// If it's odd, we print this message.
Console.WriteLine("The square is odd.");
}
}
}
Solution: Relevant Comments.
using System;
public class RandomNumberEvenOddCheck
{
public static void Main()
{
// Generate a random number between 1 and 100.
Random random = new Random();
int randomNumber = random.Next(1, 101);
Console.WriteLine($"Random number: {randomNumber}");
// Calculate the square of the random number.
int square = randomNumber * randomNumber;
Console.WriteLine($"The square of the random number is
{square}.");
// Check if the square is even or odd.
if (square % 2 == 0)
{
Console.WriteLine("The square is even.");
}
else
{
Console.WriteLine("The square is odd.");
}
}
}
Comments that Duplicate Code:
- Mistake: Writing comments that merely duplicate what the code does, providing no additional value.
- Solution: Comments should provide insights beyond what the code itself conveys. Avoid reiterating the code's logic and focus on explaining the why, not the what.
- Tools: GitHub's #CodeQL (an advanced static analysis engine) or Intellij Qodana can be integrated into the code review process to understand the context of the code and find duplicate comments.
Code Example: (Language: #Python)
Mistake: Copying Code's Logic, No Additional Value Provided.
# This view retrieves a list of products from the database
def product_list(request):
# Get all products using Product.objects.all()
products = Product.objects.all()
return render(request, 'products/list.html', {'products':
products})
Solution: Comments with Additional Value.
领英推荐
def product_list(request):
# Retrieve a list of products from the database for display on
#the page
products = Product.objects.all()
return render(request, 'products/list.html', {'products':
products})
Not Showing the Intent of Developers:
- Mistake: Writing comments that don't convey the developer's intent.
- Solution: Explain the intent behind your coding decisions, describe any underlying algorithms or strategies, and address the problem the code aims to solve. This helps fellow developers understand the context and purpose of your code.
- Tools: Code review and collaboration platforms (e.g., GitHub, GitLab) can be useful to make your intent clearer.
Code Example: (Language: #Python)
Mistake: No Mention of 'Why' the Code is Written.
def compute_interest(balance):
if balance < 1000:
return balance * 0.01
elif balance < 5000:
return balance * 0.02
else:
return balance * 0.03
Solution: Explaining the Reasons and Intent.
def compute_interest(balance):
"""
Calculate interest on a given balance using tiered interest
rates.
Tiers are decided based on the bank's promotional strategy to
incentivize keeping a higher balance:
- Balances below $1000: 1% interest rate
- Balances from $1000 to $4999: 2% interest rate
- Balances $5000 and above: 3% interest rate
Note: This is a simple interest calculation and doesn't take
into account compound interest.
Parameters:
- balance (float): The account balance.
Returns:
- float: The interest accrued on the balance.
"""
if balance < 1000:
# 1% interest for balances below $1000
return balance * 0.01
elif balance < 5000:
# 2% interest for balances between $1000 and $4999
return balance * 0.02
else:
# 3% interest for balances $5000 and above
return balance * 0.03
Comments for Bug Fixes:
- Mistake: Neglecting to document bug fixes in the code.
- Solution: Whenever you fix a bug, document it in a comment alongside the code changes. Include information about the bug, its impact, and the solution applied. This helps future developers understand the context of the change.
- Tools: #Jira, #Trello allow you to create, track, fix and document issues for each bug.
Code Example: (Language: #Java)
# Bug Fix: Issue with user authentication failing when using special
# characters in the password.
# Description: Previously, our authentication system did not handle
# special characters in passwords correctly.
# This led to unexpected failures during login for users who had
# special characters in their passwords.
# Impact: Users with special characters in their passwords were
# unable to log in, leading to frustration and support requests.
# Solution: Modified the password validation function to properly
# handle special characters.
# Added a new regex pattern to allow special characters in passwords
# and updated the validation logic accordingly.
def validate_password(password):
"""
Validates the user's password.
Args:
password (str): The password to validate.
Returns:
bool: True if the password is valid, False otherwise.
"""
# Updated regex pattern to allow special characters
pattern = r"^[a-zA-Z0-9!@#$%^&*()_+{}\[\]:;<>,.?~\\-]+$"
if re.match(pattern, password):
return True
else:
return False
Inconsistent and Long Comments:
- Mistake: Writing excessively long and inconsistent comments in the code.
- Solution: Choose a commenting style ?or a code linter that suits best for you and your team and stick to it. Aim for writing concise comments that provide meaningful explanations. Break down complex explanations into multiple shorter comments when necessary.
- Tools: Code Style Guides (e.g. Pep 8 with Flake8 for Python) and comment formatting tools (e.g. DocFormatter for Python) can help in promoting uniform and concise code commenting.
Code Example: (Language: #Python)
Mistake: Writing Long and Inconsistent Comments.
import numpy as np
# This function takes two numpy arrays as input and performs
# element-wise multiplication.
# It then calculates the mean of the resulting array and returns the
# mean value.
def calculate_mean_of_product(array1, array2):
# Loop through each element of the arrays and multiply them.
product_array = np.multiply(array1, array2)
# Calculate the sum of all elements in the product array.
sum_of_elements = np.sum(product_array)
# Count the number of elements in the input arrays.
num_elements = len(array1)
# Calculate the mean by dividing the sum by the number of
# elements.
mean_value = sum_of_elements / num_elements
# Return the mean value.
return mean_value
# This is a test example.
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([5, 4, 3, 2, 1])
result = calculate_mean_of_product(array1, array2)
print("The mean of the product is:", result)
Solution: Consistent and Concise Commenting Style.
import numpy as np
def calculate_mean_of_product(array1, array2):
"""
Calculate the mean of the element-wise product of two arrays.
Args:
array1 (numpy.ndarray): The first input array.
array2 (numpy.ndarray): The second input array.
Returns:
float: The mean value of the product of the two arrays.
"""
# Calculate the element-wise product of the input arrays.
product_array = np.multiply(array1, array2)
# Calculate the sum of the elements in the product array.
sum_of_elements = np.sum(product_array)
# Calculate the mean value by dividing the sum by the number of
# elements.
num_elements = len(array1)
mean_value = sum_of_elements / num_elements
return mean_value
# Example usage:
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([5, 4, 3, 2, 1])
result = calculate_mean_of_product(array1, array2)
print("The mean of the product is:", result)
Comments With Spelling and Grammatical Errors:
- Mistake: Neglecting spelling and grammar in comments.
- Solution: Professionalism and readability are enhanced by well-written comments. So, pay attention!
- Tools: Text Editors with built-in spell checkers and @Grammarly or similar proofreading tools can greatly help in reducing such errors.
Code Example: (Language: Python)
Mistake: Neglecting Spelling Mistakes.
def calcualte_tax(income):
# Caluclate income tax
return income * 0.2
Solution: Comments Written with Correct Spellings and Grammar.
def calculate_tax(income):
# Calculate income tax
return income * 0.2
Omitting References and External Links:
- Mistake: Failing to mention references to external sources or dependencies.
- Solution: When your code relies on external libraries, APIs, or resources, always include comments that mention the source or provide a reference. This informs other developers about the dependencies and helps them find relevant documentation or resources when needed.
Code Example:? (Language: #JavaScript)
Mistake: No Mention of References.
// Importing the fs (file system) module for file operations
const fs = require('fs');
// Reading a file using the fs module
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file.');
} else {
// Mistake: Failing to mention references to external
// sources or dependencies.
console.log('File contents:', data);
}
});
Solution: Mentioning the References.
// Importing the fs (file system) module for file operations
const fs = require('fs');
// Reading a file using the fs module
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file.');
} else {
// Mentioning the source of the file used
// Reference: example.txt
console.log('File contents:', data);
}
});
The journey of a thousand miles starts with a single step. As your code evolves, comments can be the perfect supporting side heroes you need, ensuring code remains maintainable, #readable, and #reusable. Save yourself from this apt saying, "When I wrote this code, only God and I understood what I did. Now only God knows."
All the best for making your life easier, more #time-efficient, and more #productive, and for creating a better #WorkLifeBalance.