Comment on Comments: why I removed my own comments


Hello Friends,

Recently I learned many things about comments, making me ashamed of my own code and comments. Many people may already know much about comments, if you are not among them, read on.

comment

Initially I did not use to write comments with the code thinking that those are not required, just occasionally I would write so that I can understand. We usually want to finish coding as soon as possible, as that is what matters in the program output. Later when I heard that comments are very important so that others can also understand the code, I started putting comments in my code liberally. But when recently I encountered some articles/book about comments I was shocked for how bad comments can be and why I didn’t think of it earlier. Below are my learning I want to share.

Comments are easier to write poorly than well, and commenting can be more damaging than helpful.” – Code Complete

Why comments are bad?

Difficult to maintain: Comments are difficult to maintain and very easy to ignore. They can easily get outdated.

//path is considered matched if the name matches with pattern and if it is folder
if(pattern == null || file.getName().matches(pattern))
{
if(type == null || ((file.isDirectory() && type.equals("Folder"))
 || (file.isFile() && type.equals("File")) || type.equals("Both")))
		matchedPaths.add(file.getPath());
}

In maintenance phase specially, we tend to forget to update them as the code changes as when we change them we know the code (well.. little bit) and comments don’t contribute to the code. We write code in a way it is easy to write, not easy to read. Even if we think of others and update the comments whenever we touch the code, others may not feel the same. And as they are not part of the code, the available tools like static code analyzer cannot detect the discrepancies between code and comments.

Some comments can be specially hard to maintain.

// Variable Meaning
// -------- -------
// xPos .......... XCoordinate Position (in meters)
// yPos .......... YCoordinate Position (in meters)
// ndsCmptng...... Needs Computing (= 0 if no computation is needed,
// = 1 if computation is needed)
// ptGrdTtl....... Point Grand Total
// ptValMax....... Point Value Maximum
// psblScrMax..... Possible Score Maximum

Introduces redundancy: Many a times I’ve seen code having comments like (including mine :|)

// set product to "base"
product = base;

// loop from 2 to "num"
for ( int i = 2; i <= num; i++ ) {
// multiply "base" by "product"
product = product * base;
}
System.out.println( "Product = " + product );

Not only it wastes the space, it can add confusion if it is not accurate. The code itself should be clear enough to understand. This was the main reason why I removed my earlier comments.

Crutches for bad code: We should have the mentality while writing code as if comments do not exist, so that the code itself is easy to follow. Someone said “Comments are like deodorant to the stinky code“. Some people use them as crutches for their bad code.

// write out the sums 1..n for all n from 1 to num
cur = 1;
pre = 0;
s = 1;
for ( int i = 0; i < num; i++ ) {
System.out.println( "Sum = " + s );
s = cur + pre;
pre = cur;
cur = s;
}

Hinders readability: Some comments look so dominant that the real code is obstructed

/*************************************************
' Name: CopyString
'
' Purpose: This routine copies a string from the source
' string (source) to the target string (target).
'
' Algorithm: It gets the length of "source" and then copies each
' character, one at a time, into "target". It uses
' the loop index as an array index into both "source"
' and "target" and increments the loop/array index
' after each character is copied.
'
' Inputs: input The string to be copied
'
' Outputs: output The string to receive the copy of "input"
'
' Interface Assumptions: None
'
' Modification History: None
'
' Author: Dwight K. Coder
' Date Created: 10/1/04
' Phone: (555) 222-2255
' SSN: 111-22-3333
' Eye Color: Green
' Maiden Name: None
' Blood Type: AB-
' Mother's Maiden Name: None
' Favorite Car: Pontiac Aztek
' Personalized License Plate: "Tek-ie"
'*************************************************/

The beauty should be in code not in comments. I’ve also seen at many places old code lies here and there commented. If it is not required now, it should be removed rather than lying and confusing others.

Then what?

Good names: Rather than comments explaining things, the code should have good, meaningful, self-explanatory names for variables, methods and classes.

What does below variables mean?

private String myString;

	public Foo(String theString) {
  	myString = theString;

  	int aPos1 = 0;
   int aPos2;
   // ...
	}

Extraction to methods/classes: Rather than having a comment for a piece of code, the code should be extracted to a method. The code should be properly re-factored time to time. Code should be properly modularized to different components, classes and methods.

For example:

private double squareRootApproximation(num) {
  root = n / 2;
  while ( abs( root - (num/root) ) > t ) {
    root = 0.5 * ( root + (num/root) );
  }
  return root;
}

instead of:

....
// square root of n with Newton-Raphson approximation
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
  r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );
....

Relying on version control system: For recording the history of code, version control systems are to be relied on, not the commented code. Many people keep the old code as commented while writing new code, which is totally unnecessary now a days.

/* public doSomething(String pre, String post)
{
  ....
}*/
public doSomething(String pre, String mid, String post)
{
  //new functioning
  ....
}

Where beneficial?

Intentions: You should mention your intention while writing code for example when you take some decision out of different alternatives. You should mention the why, not the what/how about the code. You can also mention the important TODOs in the comments.

//Using technique A because of limitations of B and C
....
....
//get current employee information
....
....
try{
...
}catch(ABCException ignored)
{
//not handled because ...
}

Consequences: You should warn about the important consequences of using some code.

//be careful, below code may impact ... as ...
....

Names insufficient: When you can’t use a function name to explain something, because otherwise_it_will_be_very_long_like_a_sentence.

Legal notices: Legal notices, like copyrights can be used as comments in the code.

 /*
  * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
  *
  ...

Standard documentation: For example Javadocs should be used in public APIs.

/**
  * Swaps the elements at the specified positions in the specified list.
  * (If the specified positions are equal, invoking this method leaves
  * the list unchanged.)  
  *
  * @param list The list in which to swap elements.
  * @param i the index of one element to be swapped.
  * @param j the index of the other element to be swapped.
  * @throws IndexOutOfBoundsException if either i or j
  *         is out of range (i < 0 || i >= list.size()
  *         || j < 0 || j >= list.size()).
  * @since 1.4
  */

Unchangeable code: If you can’t change some code for example library call results, but you want to put clarification, you should use the comments. 

//this gets the info related to ...
....

You may also find below articles interesting:

http://www.codinghorror.com/blog/2008/07/coding-without-comments.html

http://www.codeodor.com/index.cfm/2008/6/18/Common-Excuses-Used-To-Comment-Code-and-What-To-Do-About-Them/2293

http://pointlessprogramming.wordpress.com/2011/03/14/on-commenting-source-code-why-commenting-is-not-bad-practice/

Happy learning, bye.

Advertisements

One thought on “Comment on Comments: why I removed my own comments

  1. Pingback: Need More Scouts for the Old Code | JavaCurious

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s