Clean Code – How to Avoid Comments on Single Lines of Code

clean codecomments

I'm trying to clean up some of my code using some best practices, and read that comments are almost always a bad idea for future maintainability. I've managed to get rid of most of them by refactoring to methods with good names.

However, there are several comments sprinkled around that explain why a single line of code needs to exist. I'm having trouble figuring out a way to get rid of these. They often follow this kind of structure:

// Needs to start disabled to avoid artifacts the first frame. Will enable after frame complete.
lineRenderer.enabled = false;

Then later on in the code I enable it.

I've thought about extracting it into a one-line method called StartLineRendererDisabledToAvoidArtifactsFirstFrame() but this doesn't seem all that clean to me.

Are there any best practices for dealing with such one-liners? Many of them explain the existence of code that on the surface looks superfluous but then actually has an important function. I want to guard against future deletion.

Sidenote: I've already run into some scenarios where refactoring/renaming has made these comments be out-of-date or in the wrong spot etc. so I definitely see why removing them would be useful.

Related but different question here:

EDIT BASED ON ANSWERS AND COMMENTS BELOW

Here's my takeaway from all the great discussion below.

  1. Comments are fine if there's not an easy way to refactor/rename for more clarity. But they should be used sparingly.
  2. Removing comments is generally a good thing. But some comments need to exist to help future readers understand the code without having to dig too deep.
  3. But they should explain the WHY, not the HOW.
  4. If the code is there for a particular reason that is very important or fixes a bug, it should probably also have a corresponding unit test anyway.
  5. Commit messages can help track why and where and how the commented code came to be.

Best Answer

You answered this yourself in the very first sentence of your question - comments are almost always a bad idea for maintainability. There are times when a quick note in the code is a good thing to include so that way a future developer can understand why something was done that way it was. This could prevent a change that introduces a problem.

Generally, I do prefer readable code and organized commits (with good commit messages) to comments in the code, simply because I've seen too many times where the comments aren't maintained as the code around them changes. But there are times when comments are appropriate. You may have just found a case where refactoring to a method is less clear than a one line comment. With fewer, more relevant comments, future developers will be more likely to read them and maintain them with the code.

Related Topic