Comments are false

If you are a programmer, there are many practices that you can hate.





Hardcoded values. Double logic. Complex inheritance hierarchies. But should comments be on this list?





A long time ago, in the days of prehistoric programming, writing comments was considered a mandatory part of writing code. When you wrote the code, it was filled with short and precise comments. Then clean code and agile programming began to rule the world. Purists screamed about the dangers of comments that filled unstructured and vulnerable code. Suddenly the comments became a mistake, an anti-pattern, a collection of outright lies.





Many developers felt cornered.





False choice
False choice

But is the choice so obvious? Or is there still a way to write comments and at the same time respect yourself by getting up in the morning? To find out the answer, let's look at how terrible code is commented and how even a bad comment can save lives.





Lazy comments

, , .





, , :





double delta = h*h-r1*r1;
double r2 = Math.Sqrt(delta);
      
      



, , . , , , :





// Calculate side length using the Pythagorean Theorem
// and put the value into variable "r2"
double delta = h*h-r1*r1;
double r2 = Math.Sqrt(delta);
      
      



- . .





. , :





double lengthSideB = Math.Sqrt(
  Math.Pow(hypotenuse,2) - Math.Pow(lengthSideA,2);
)
      
      



:





double sideA = Pythagoras.GetLengthOfSide(hyptenuse, sideB);
      
      



? ! - , , . , . , . - - .





. , , , . , - - . , , . , . , . :





/**
  * Constructor.
  * 
  * @param name (required) brand name of the product. Must have
  * content. Length must be in range 1..50. 
  * @param price (optional) purchase price of the product.
  * @param units (required) number of units currently in stock.
  * Can not be less than 0.
*/
public Product(string name, decimal price, integer units)
{
   ...
}
      
      



, , . - , . . , , .





. , . . . . , , - . API. , , . . - , . , API , , , . . , - . , . .





ยซ - ยป - , .





. , - :





// to match ITG1's late arrows.  -K
GlobalOffsetSeconds=-0.006
      
      



, - , . - , , , , . , , , . . , , , . , - , , , , ? - , , , , , .





, , , , . , , , . , . - , - .





โ€œI spent some time this weekend looking at very well-named, very clean, uncommented code implementing a research algorithm. Iโ€™m high-level familiar with it, the guy sitting next to me was the inventor, and the code was written a few years ago by someone else. We could barely follow it.โ€ โ€” Paul Nathan





, , . , , , . . , . , , . .





, . . :





  • ( )





  • ( )





  • ( IDE)





The main question is simple. Is it worth paying for comments? Opinions differ, but if you use comments thoughtfully and intelligently - if you use them to reduce the cognitive load of your code, rather than counteract bad practices - they can add value to even the cleanest code.












All Articles