Comments In Your Code

Why you should keep them to a minimum

Daan
Daan
Jul 11 · 4 min read

Comments Are Failure to Express Ourselves

Please note the word failure in the previous sentence. Because that’s what comments are. A failure to express ourselves. The only reason that we have comments in our code is that we don’t know how to express ourselves without them.

Comments do not make up for bad code

Sometimes, the motivation to write comments is bad code. Sometimes, we write code and we know it’s a mess.

Explain yourself in code

It takes only a few seconds to explain most of your intent in code.

// Check to see if game is finished and player can not spawn again
if ($game->status == GameStatus::FINISHED && $player->lives == 0)
if ($game->isFinished())

Bad Comments

1. Commented-out code

There is one simple practice when it comes to commenting-out code: don’t do it.

2. Noise comments

Some comments that you see are just noise. They restate the obvious and serve no real purpose.

public function __construct() {
// Call the parent constructor
parent::__construct();
}
/** The users name */ 
private $name;
/** The users age. */
private $age;

3. Redundant comments

A redundant comment is a comment that is not more informative than the code. It does not justify the code or provide intent. These comments only clutter the code.

// Method that return true if when stream is open
// Throws an exception if stream is closed
public function waitForStreamClose() {
if (!$this->closed) {
return true;
}
throw new Exception('Stream still open');
}

4. Journal comments

Sometimes, developers add a comment in the top section of their file every time they edit it. Don’t do this. We’ve got version control systems for this.


Good comments

Sometimes comments are beneficial or necessary.

// Copyright (C) 2019 by Someone, Inc. All rights reserved. 
// Released under the terms of the GNU General Public License

1. Informative comments

It could sometimes be useful to provide basic information with a comment.

2. Warning

When you’re working with multiple developers on a project, you could use a comment to warn other developers about certain consequences.

// Takes a really long time to finish, only run at night.
private function synchroniseProducts()

3. To-do

To-do comments are for tasks a developer thinks should be done, but for some reason can’t be done at this moment.


Conclusion

This was my article about using comments in your code. Even though there are some forms of good comments, I think that you should try to minimize the usage of comments in general.

Better Programming

Advice for programmers.

Daan

Written by

Daan

Backend developer from The Netherlands. Crypto enthusiast.

Better Programming

Advice for programmers.