Should You Comment Your Code? [EXAMPLES]

When debating about commenting code, some developers say you should ALWAYS write comments. Others say the code should be clear enough, with comments only as a "last resort". Let's take a look at examples.

I've identified three different "types" of comments, and in all of those cases we have good and bad examples. So here they are.


Type 1. Documentation Comments

These are special comments that are used to document code. They are usually written in a specific format, with purpose to provide additional information on the context.

These types of comments are pretty common in Laravel configs.

config/sanctum.php

/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
 
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),

They may also include examples like in the Lodash library.

_.partition([1234], n => n % 2);
 
// → [[1, 3], [2, 4]]

Another category of documentation comments is referred to as annotations and are used by tools to generate documentation like Swagger or provide additional context for IDE.

/**
* @OA\Info(title="My First API", version="0.1")
*/
 
/**
* @OA\Get(
* path="/api/resource.json",
* @OA\Response(response="200", description="An example resource")
* )
*/

To maintain consistency, documentation comments must follow the same standard.

The thing to keep in mind is that documentation comments can clutter your code and make it more difficult to read, especially for those who are responsible for maintaining it.


Type 2. Clarification Comments

These are used to explain a confusing or complex section of code. They aim to provide additional context to help developers understand the code more easily, especially if the code was written some time ago.

Good example

This helps to avoid obvious code "improvements" which may later introduce bugs and result in a full cycle of finding where the bug comes from and undoing the change.

function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1])
return map
}

Bad example

Comment in this case is redundant and the code is self-explanatory enough.

// Finds user by id and assigns it to a variable $user
$user = User::find($id);

Cat Comment

This one is not related to the code. It serves no purpose trying to explain what code could be there.

// If $roleId doesn't exist admin can create a new role
User::roles()->attach($roleId);

Another case of bad usage of comments is when people try to document poorly written code. Could you tell what this function does if there was no comment? Maybe, but not just by looking at it. Even the comment doesn't tell what the hell is that 22/7 (pi's approximate value as a fraction) expression.

/**
* Calculates the volume of a cylinder
* $a is the radius
* $b is the height
*/
function ccv($a, $b)
{
return $a * $a * $b * 22 / 7;
}

Instead, just try to write a better code by giving proper function and variable names. One-character-long meaningless variables do not make your code run faster, but clear code will improve application development time.

function getCylinderVolume($radius, $height)
{
return pi() * $radius ** 2 * $height;
}

Immediately looks better, right?


Type 3. Fun comments

Sometimes developers get creative and leave humorous and useful comments.

Good example

Here's the most famous piece to discourage other developers to modify the code as this has been attempted many times.

// Dear maintainer:
//
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 42

Laravel also has more sophisticated "fun" comments. As Caleb Porzio observed:

One of my favorite things about Laravel has always been Taylor's obsessive 3-line code comments. (those pretty little comments where each line is exactly 3 chars less than the previous).

/*
|-----------------------------------------------------------------------------
| How to write your code comments like Taylor:
|-----------------------------------------------------------------------------
|
| In Laravel, there are 598 three-line code comments. The first line of each
| is ~74 characters long. Each subsequent line has three characters fewer
| than the one above it. Whether trailing periods count is your choice.
|
*/

Bad example

Well, this might be fun if it is not your code and makes the whole code base look unprofessional.

// This code sucks

Conclusion

So, generally, you should add comments in all the cases similar to what I mentioned as "good examples" in this article. Do you agree?

What other "fun" or "bad example" comments you've seen in the wild? Share in the comments (pun intended) below :)

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1056 lessons, total 42 h 44 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials