Commenting Your Code

Documenting your code is an essential part of computer programming. Documenting means writing English comments about your code that explain what it does. It makes your code easier to maintain and update. It also makes your code easier to understand, both for yourself and for others working on the same code. This section of the code quality guide will show you how to write good comments.

There are two ways to write comments in Java; single-line and multi-line comments:

// This is a single-line comment
/* This is a
multi-line comment */

Either way is fine for writing comments, but generally programmers like to stick with one or the other for consistency.

⬆ back to top

Header & Class Comment

You should have two comments at the beginning of your file before your program. The first is the header comment, which provides identifying information about you as the author of the program, similar to a header you would write for an essay. You should include your name, the date, the class (CSE 142), your TA's name, and the name of the program (the assignment). The second is a class comment that provides a high-level description of what your program does. An important thing to remember is that your class comment should only describe what your program does, not how it does it. A client of your code doesn't care and shouldn't need to know how your code works (ie. using Scanners/PrintStreams, some sort of loop or conditional structure, class constants, etc.). Including these implementation details in your comment also makes it difficult to change your code later on and still have accurate comments. Omitting implementation details allows you to change how you implement your code without having to change your documentation. An example of a good class header could be:

// Student Studentname
// 11.20.2018
// CSE 142 Section XX
// TA: Wrett Bortzman
// IMDB Search
// Searches a text file containing information about the top 250
// rated movies on IMDB for movies containing a particular word in the title,
// then prints the results to an output file.

import java.util.*;
import java.io.*;
public class ImdbSearch {...}

Note: These comments should come before all code, including import statements. You can see the full code for ImdbSearch here.

⬆ back to top
Class Comments for Objects

Objects are classes just like other code, but they represent something - some object. So just like any other class, you should have a class comment that describes what your class represents - in the case of an Object, what it represents. Your class comments for some objects may be shorter than some of the class comments you've written for other programs - this is probably fine, as long as your class comment is describing what the class represents. For example, for the Point class, a complete class comment could be:

// <header comment>
// A class to represent a point on the x-y coordinate plane.
public class Point {...}
⬆ back to top

Method Comments

You should include a comment for every method in your program, except main (main should be a concise summary of the program, and your class comment should already describe what your program does). A method comment should describe what a method does, information about the parameters it takes (if it takes parameters), and what is returned by the method (if the method returns). For parameter comments, make sure to explicitly name and describe the purpose of all parameters -- what information does this parameter provide? Think of commenting on parameters as providing a brief definition.

Note that just like with class comments, you should avoid talking about implementation details in your method comments for the same reasons. The client does not need to know how your method works and omitting implementation details allows you to change how you implement your code without changing your code documentation.

Take for example the method roundN

public static double roundN(double num, int digits) {
    return Math.round(num * Math.pow(10, digits)) / Math.pow(10, digits);
}

roundN rounds a given number to a given number of digits (you don't need to understand anything about how this method works, so it's fine if the method itself makes no sense to you right now). Here are a few different styles of good, complete comments for this method:

// Rounds a given number num to the given number of digits and
// returns the rounded number
public static double roundN(double num, int digits) {...}
// Rounds a given number to the given number of digits.
// Returns the rounded number.
// Parameters:
//    double num - the number to be rounded
//    int digits - the number of digits to round to
public static double roundN(double num, int digits) {...}
/**
 * Rounds a given number to a given number of digits.
 * @param num - the number to be rounded
 * @param digits - the number of digits to round to
 * @return the rounded number
 */
public static double roundN(double num, int digits) {...}

The last comment in what is called Javadoc notation. Javadoc uses multi-line comments that start with /**. Javadoc gives you a really nice template for commenting, but is not at all necessary for your comments in this class. Javadoc also allows you to generate documentation files for your program similar to the official Java docs. You can do this in jGrasp by hitting the button that looks like an open book in the toolbar or from menus File > Generate Documentation. You can learn more about Javadoc documentation here.

⬆ back to top
Instance Method Comments

Instance methods are non-static methods that we declare in Object classes. Just like any other method, instance methods should have method comments that describe what the method does, what parameters the method takes (if it takes any), and what the method returns (if it returns anything). Take, for example the fight method from the Rabbit Critter. Rabbits will attack using SCRATCH if the opponent is a Bird or a Vulture:

// Returns the Attack SCRATCH or ROAR based on the opponent:
// will SCRATCH if the opponent is a Bird or a Vulture, and ROAR otherwise
//      opponent - the String representation of the opponent Critter
public Attack fight(String opponent) { 
...
}
⬆ back to top
Constructor Comments

Similar to instance methods, constructors are methods, they just function a little differently than other methods. Just like any other method, constructors should have method comments that describe what the method does (usually just constructing that object, and any other important behavior of the constructor), and what parameters the constructor takes (if it takes any). Note that constructors do not return anything, so there's no need for a return comment. Take, for example the constructor for the Frog Critter. Frogs take an age as a parameter that represents how old the Frog is:

// Constructs a new Frog
// Parameters:
//      age - determines the frogs movement
public Frog(int age) { 
...
}
⬆ back to top

Inline Comments

Sometimes it can be helpful to have more specific comments within your code, usually within your methods, that explain more complex lines or sections of code. These are called inline comments. Some good places to include inline comments would be:

  • class constants
  • strange initializations
  • loop priming (initializing variables to certain values to start a loop)
  • complex expressions
  • confusing tests and conditions

This is not an exhaustive list -- if you have code you feel needs explaining, that's a good place for an inline comment. Try putting yourself in a client's shoes and see if anything might be confusing.

An inline comment can be placed either at the end of the line of code it explains or directly above the code it explains (this is more preferable if putting it on the same line would make that line too long). Here are some exampes:

public static void printRandomNums(int nums, int limit) {
    Random r = new Random();
    int max = 0;
    for (int i = 0; i < nums; i++) {
        // generates a random number from 1 - limit
        int num = r.nextInt(limit) + 1;

        if (max < num) {
            max = num; // keeps track of max generated number
        }
        System.out.print(num + " ");
    }
}
⬆ back to top

Comment Templates

Note: You should replace any text surrounded by < and > with the relevant information for your program.

Header and Class Comment:

This is a good example of what you should include in your header and class comment and how to format them:

// <Your Name (First and Last)>
// <Date>
// CSE 142 Section <Your Section>
// <Your TA>
// <Program Name>
// <high level description of your program goes here>
Method Comments:

There are a few options. These two are both great styles for method comments, and the second uses the Javadoc notation introduced earlier:

// <description of method>
// <what the method returns (if applicable)>
// parameters:
//    <parameter1> - <description of parameter1>
//    <parameter2> - <description of parameter2>
//    etc...
/**
* <description of method>
* @param <parameter1> - <description of parameter1>
* @param <parameter2> - <description of parameter2>
* etc...
* @return <what the method returns (only if applicable)>
*/

Your method comment does not have to be in one of these formats. These are just two formats that include all the important information for a method comment.

⬆ back to top

Things to Avoid in Comments

Language

There are some phrases you should avoid in your comments. Saying "this method" or "this program" in a method or class comment does not add any valuable information; we already know you're talking about the method/program, so you should just say what it does. You should also avoid saying that a method "should" do something. You should comment on what your method does do, not what it should.

Implementation Details

As mentioned previously, you should never include implementation details in class and method comments. The client does not need to know how your code works, and omitting implementation details allows you to change how you implement your code without changing your code documentation. Here are some examples of things you should never include in comments:

  • Control structure usage (if, for, while)
  • methods used
  • "static method"
  • "calls"
  • "loop"
  • "class constant"
  • "extends"

Finally, you should absolutely never refer to the spec in your comments. The spec is for you, and you should assume that a client of your program has no knowledge of it. We also hope that this is clear, but your comments should be your description of your program, so copying text verbatim from the spec is considered academic misconduct and not allowed.

⬆ back to top

Contributors