Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Comments

One part of the getEndDate method that could use clarification is the calculation for the number of days to add to the session start date.


   int numberOfDays = 16 * 7 - 3;

To another developer that has to maintain this method, the mathematical expression is not immediately obvious. While the maintainer can probably figure it out in a few minutes, it's far less expensive for you as the original developer to explain what you were thinking.

Java allows you to add free-form explanatory text within the source file in the form of comments. The compiler ignores and discards comments encountered when it reads the source file. It is up to you to decide where and when comments are appropriate.

You can add a single-line comment to the numberOfDays calculation. A single-line comment begins with two forward slashes (//) and continues to the end of the current source line. Anything from the first slash to the end of the line is ignored by the compiler.


   int numberOfDays = 16 * 7 - 3;  // weeks * days per week - 3 days

You can place single-line comments on a separate line:

// weeks * days per week - 3 days
int numberOfDays = 16 * 7 - 3;

However, comments are notorious for being incorrect or misleading. The above comment is a perfect example of an unnecessary comment. A better solution is to figure out a clearer way to express the code.

Icon

Replace comments with more expressive code.

One possible solution:

final int sessionLength = 16;
final int daysInWeek = 7;
final int daysFromFridayToMonday = 3;
int numberOfDays = 
   sessionLength * daysInWeek - daysFromFridayToMonday;

Hmmm. Well, it's more expressive, but I'm not sure that daysFromFridayToMonday expresses exactly what's going on. This should demonstrate that there's not always a perfect solution. Refactoring is not an exact science. That shouldn't stop you from trying, however. Most changes do improve the code, and someone (maybe you) can always come along after you and figure out an even better way. For now, it's your call.

Java supplies another form of comment known as a multiline comment. A multiline comment starts with the two characters /* and ends with the two characters */. Everything from the beginning slash through to the ending slash is ignored by the compiler.

Note that while multiline comments can nest single line comments, multiline comments cannot nest other multiline comments.

As an example, the Java compiler allows the following:

int a = 1;
/*  int b = 2;
//  int c = 3;
*/

while the following code will not compile:

int a = 1;
/*  int b = 2;
/*  int c = 3;  */
*/

You should prefer single-line comments for the few places that you need to annotate the code. The multiline comment form can then be used for rapidly "commenting out" (turning off the code so that it is not read by the compiler) large blocks of code.

  • + Share This
  • 🔖 Save To Your Account