by Francesco Agnoletto

Bad comments and how to fix them

A short guide on how to make your codebase more readable

I’ve talked about the importance of code comments here.

As developers, we have a vast array of solutions to enhance the readability and safety of our code.
Below there are some real-world examples of bad comments, and how how they can be improved.

Commented out code

Pretty simple, code that has been commented out. It could have been important or not, but it does not offer anything now.

commented-out-code

This code can be deleted.
If you want to keep it around, it will still live in your git history. Make sure to give it a nice commit so you can easily go back to it.

We do not need to pollute the codebase with useless code. It increases file size and makes everything harder to understand.

fixed-commented-out-code

Description comment

Some comments describe what a variable could describe with the same effectiveness.
Having well-named variables is better than hard to read code with comments in it.

variable-comment

The if statement looks pretty complex, thus deserving a comment its behavior.
Abstracting the condition in a variable can give the same information as the comment.

fixed-variable-comment

Warning comments

Other comments act as warnings, “do not touch this because of reasons”.
This is a pretty weak use of comments. They either deter developers from improving the code or they just get ignored.

warning-comment

We can solve this is by writing a test with fake data containing the exception stated by the comment.
If someone modifies the code, the test will fail. This gives us more confidence in our deployments than a flimsy warning comment.

fixed-warning-comment

Final notes

Comments are very valuable and should be used across any codebase. But some comments are just band-aids masking the real problem. One of the skills of a good developer is identifying where a comment is needed and where it is not.