- read

Good vs. Bad Comments: How Professionals Approach Code Comments

Victor Timi 52

Good vs. Bad Comments: How Professionals Approach Code Comments

“If comments are inherently considered a bad practice, why do they exist in the first place?”

Victor Timi
Level Up Coding
Published in
5 min read21 hours ago

--

Banner Image (Good vs. Bad Comments)
Good vs. Bad comments

Comments are commonly employed to clarify code that is difficult to understand. But, at times, they end up being redundant.

One of the primary reasons why using comments isn’t generally recommended is because some professionals see them as clutter in the codebase. This belief is rooted in maintainability concerns, as comments require ongoing updates whenever modifications are made to the codebase. Many professionals advocate for writing elegant, self-descriptive code that minimizes the need for extra comments.

However, when I think about good comment practice, I ask myself, ‘Will I be adding comments to let my team know what my code is doing, or let them know ‘why’ I am solving this problem this way?’ In general, the answer is to always address the ‘Why.’ Discussing the ‘why’ behind a specific approach adds depth and meaning to a comment, making it easier for colleagues to collaborate, troubleshoot, or make future improvements.

Contents: Bad comment practice | When to use comments | Conclusion

What types of comments constitute bad practice?

There is much to ponder when distinguishing between good and bad comments. In its simplest explanation, if your comment is telling “What” code is like, then you are using comments incorrectly. If your code is a bit difficult to understand at first glance, consider letting it self-document instead of overloading your codebase with comments.

Self-documented code is code where variables, functions, or objects are given names that clearly explain their purpose and what the code is doing.

Using self documented code functions are much more readable when they are written in verbs because they carry out an action, like “GetRandomUser”, “PrintInvoice”, “SortArray”, “ValidateEmail” etc.

Here are common types of poor commenting practices:

Visual Markers

Visual Markers are comments that tells you what the code does. They are typically used when the code itself can’t easily convey its purpose or can’t simply explain itself.

A typical visual marker often looks like this:

//this is a variable that reads a number
let number: number

Yeah, typically like that.

Another often use case of visual markers is this:

// Check if the user has admin privileges
if (role === 2) {
grantAdminAccess(user);
}

This code check if a user has admin privileges. Think of it like a chat app where users can have roles such as admin, moderator, or member.

In this context, the number “2” might not be immediately clear upon first glance. So, when someone needs to perform mental calculations to understand your code, it’s a good idea to consider using descriptive variables instead, just like this:

const ADMIN_ROLE = 2;

if (role === ADMIN_ROLE) {
grantAdminAccess(user);
}

Now, the latter appears significantly cleaner simply by substituting those ugly comments with more descriptive variables.

Now, take a moment to examine the code below and see if you can grasp it at first glance:

// Examine if the user, who may or may not be a premium member, shall, or shall not, be deemed a premium member, based on the criteria:
// 1. Subscription canceled, which may or may not be true, or,
// 2. The current date and time, which may or may not be greater than or equal to the highly specific and arbitrary date and time string "2021-12-12T00:00:00.000Z".

if (
(user.subscriptionCanceled == true) ||
(new Date().toISOString() >= "2021-12-12T00:00:00.000Z")
) {
user.isPremiumMember = !(user.isPremiumMember ? false : true);
}

You might eventually decipher it after a minute or so. However, why spend minutes deciphering this code when it can be simplified to provide instant clarity.

const isSubscriptionCanceled = user.subscriptionCanceled === true;
const isPremiumSubscriptionExpired = new Date().toISOString() >= "2021-12-12T00:00:00.000Z";

if (isSubscriptionCanceled || isPremiumSubscriptionExpired) {
user.isPremiumMember = !user.isPremiumMember;
}

I understand that it may not seem like a significant issue in your codebase, but when you have a lot of Visual Markers scattered throughout a large codebase and repeated in multiple areas, they can lead to a codebase that is challenging to maintain, especially as changes begin to occur.

Another prevalent form of poor commenting is the presence of Zombie Code.

Leftover Code/Zombie Code

Zombie code are code that has been commented out especially from developers that don’t want to get over their old logic.

// const isSubscriptionCanceled = user.subscriptionCanceled === true;
// const isPremiumSubscriptionExpired = new Date().toISOString() >= "2021-12-12T00:00:00.000Z";

// if (user.subscriptionCanceled || isPremiumSubscriptionExpired) {
// user.isPremiumMember = !user.isPremiumMember;
// }

When you have comments like this in your codebase, you’re leaving your codebase vulnerable to further deterioration. This is because it can confuse future developers or yourself: Should the commented-out code be uncommented? Or should it be deleted?. As a developer, It’s easy to forget about Zombie code because it lingers in your codebase, occupying space like matter, often with no clear purpose.

When to Use Comments in Your Code:

If comments are generally regarded as a bad practice, why do they exist in the first place? In reality, comments aren’t inherently bad; they have their rightful place but are often composed unprofessionally.

While complex functions may warrant explanations, crafting them elegantly so that they don’t resemble Visual Markers is what makes a comment great.

What makes visual markers bad comment practice is because it tells you “What” your code does. Your comment should explain “Why” your code exists in the first place.

Here are a few indications on when you should use a comment:

For Understanding Complex Logic

In cases where parts of your code are complicated and hard to understand, it’s helpful to add clear explanations using comments. These comments make it easier for anyone to quickly grasp what the complex code does. Leveraging industry standards like JSDoc, TSDoc, or other documentation tools can enhance the coding experience by offering valuable guidance and assistance for complex code.

To Explain Code Behavior

In situations where code doesn’t perform as expected, and complete removal isn’t the solution, but rather minor adjustments are required for it to function correctly, judicious comments can provide a valuable means of explanation.

Legal Considerations:

Legal comments become especially important when using open-source libraries or code with specific licensing requirements. These comments clarify the terms under which the software can be used, ensuring compliance with licensing agreements.

In Conclusion

Comments are instrumental in speeding up code comprehension, especially in complex scenarios. They act as helpful guides, unraveling intricate code and establishing a shared language within the codebase. Code documentation tools like JSDoc, TSDoc, and others provide invaluable support by offering IntelliSense, giving insights into code purpose when you hover over it.

Embracing effective commenting practices not only enhances code clarity but also encourages smoother collaboration and improved maintainability, making them an indispensable asset in the world of programming.

See you next time…