On Comments

I received this email today: 

I bought your book “Teach yourself C++ in 1 Hour a Day” and on page 37 you say  that “The bottom line is that comments should not say what is happening, they should say why it is happening”. Can you kindly elaborate this further?

The answer comes in two parts. 

First, and to directly answer the question, it is the difference between writing

public void SomeFunction(object myObject)
{
   // assign the cubic feet to a local variable
   double cubicFeet =  myObject.CubicFeet;
}

 

in which the comment adds no information at all, and in writing this:

public void SomeFunction(object myObject)
{
   // create copy of the cubic feet
   // property for local manipulation without
   // modifying original value
   double cubicFeet = myObject.CubicFeet;
}

 

although this is not an ideal example because if you know the rules of C++, then even this explanation is redundant.  And that brings me to the second part of my answer. 

If you assume your reader knows the language, and if you name your methods well and your variables well, I would argue that comments are (almost?) always redundant…

public void ManipulateCubicFeetLocally(object MyObject)
{
  double cubicFeet = myObject.CubicFeet;
}

 

In this case, I can’t see the need for any comment at all.  The name of the method and the variable make clear what the local variable is and what it is for. 

This idea holds in C# as well as C++. of course.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.

3 Responses to On Comments

Comments are closed.