Sunday 2 September 2018

Cleaner code - Comments

I truly believe that if the code is written well enough, comments should not be required at all. Not all comments are bad. They can be useful, i.e. they add additional details, information, caveats or provide example inputs (e.g. good/bad inputs for complex regex). Sadly, most of the time comments are put in with little thought, added automatically and are not kept up to date. It has become a bug-bear of mine and this nonsense has to stop! The following are the types of comments that bug me the most!

Bad comments
Comments should be informative, explain the intent or clarify what the code is doing. Sadly this is not always the case. Please be on guard to remove these variances of bad commenting:
Journal comments
We don't need to document when code was created, last updated or by whom. That's what versioning systems are for.
* Changes (from 11-Oct-2001)
* --------------------------
11-Oct-2001 : Re-organised the class and moved it to new package
*               com.jrefinery.date (DG);
05-Nov-2001 : Added a getDescription() method, and eliminated NotableDate
*               class (DG);
12-Nov-2001 : IBD requires setDescription() method, now that NotableDate
*               class is gone (DG);  Changed getPreviousDayOfWeek(),
*               getFollowingDayOfWeek() and getNearestDayOfWeek() to correct
*               bugs (DG);
Attributions and Bylines
/* Added by Rick */
Thanks Rick. Remove anything like this.
Noise / Redundant comments
Sometimes you see comments that are nothing but noise. They restate the obvious and provide no new information.
/**
  * Returns the day of the month.
  *
  * @return the day of the month.
  */
 public int getDayOfMonth() {
   return dayOfMonth;
}
Consider what purpose does the comment serve. If it’s not more informative than the code, remove.
Misleading comments
These are possibly the worst kind as they may state a fact about the code that may have been true once but is now false. Too often the comments get separated from the code they describe and become orphaned blurbs of ever-decreasing accuracy.
JavaDocs in Nonpublic code
Javadocs are useful for public APIs. Generating Javadoc pages for the classes and functions inside a system is not generally useful, and the extra formality of the Javadoc comments amounts to little more than a distraction. Comments like this just clutter up the code, propagate lies, and lend to general confusion and disorganization.

No comments:

Post a Comment