Why You Should Limit Your Use of Comments to Make Cleaner Code as a Developer

Tomasz Dobrowolski
3 min readApr 1, 2022
Photo by Luca Bravo on Unsplash

I used to think that good code involved adding a lot of detailed comments.

After reading Robert C. Martin's book titled Clean Code, I realised I was using comments in the wrong way.

Here are the reasons why:

Limit your use of comments, explain yourself in code instead

Comments tell lies, code does not.

Comments are used to explain what the code does, but if they are not used correctly, they can spread misinformation about the code. Here’s how:

  1. Bad explanations — The comment does not explain what the code does. Confusing the reader, and making them interpret the code for something else.
  2. Time — When you first write a function, you put a comment to state exactly what the function does. If the codes functionality changes, the likely scenario is the comment never gets updated. Meaning the comment is now a lie.

Code does exactly what it says. Code may be hard to interpret, but it never lies.

That’s why it is vital to use good naming conventions and formatting, to make code easy to read and interpret.

Look at the following examples:

Bad Code:

//Function receives a list of albums and an artist. It then loops through the list of albums and returns a list of albums which have the same artistprivate function loopFunction($items, $artist)
{
$artists = [];
foreach($items as $item){
if($item['artist'] === $artist) {
array_push($artists, $artist);
}
}
return $artists;
}

As you can see the code is vague through bad naming conventions, no type declaration or return type specification. Therefore a comment needs to be added to explain it.

Better Code:

private function findAllAlbumsFromArtist(array $arrayOfAlbums, string $artist): array
{
$arrayOfAlbumsFromArtist = [];
foreach($arrayOfAlbums as $album){
if($album['artist'] === $artist) {
array_push($arrayOfAlbumsFromArtist, $artist);
}

--

--

Tomasz Dobrowolski

I break down Software Engineering and Tech concepts | Backend Engineer 🐘