Motivation

In Java, comments are ignored by the compiler meaning that comments are not intended for the behavior of a program. Instead, comments are intended to be a helpful explanation of what your code does and how to use it. Writing good comments is intended to help clients of your code.

There is no single way to write a helpful comment. It may help to think from the client’s perspective. The client can read through your implementation to get an idea of what the code does, but the comment is meant to save the hassle and offer context. As such, a helpful question to ask when writing comments is, “if a client could not see my code implementation and just had this comment, would they be able to use the hidden piece of code?”. Asking this question reveals that we should comment on the behavior of the method, the inputs to the method, and the outputs of the method.

Comment Formatting

There are three main comment fomatting styles:

// Comment
// Style
// #1


/* Comment
   Style
   #2 */

/**
 * Comment
 * Style
 * #3
 */

In this course, we welcome you to use your personal commenting style! Make sure to keep your commenting style reasonable and consistent throughout your code.

Header Comments

At the top of all programs, for this class, you should have a header comment which includes your name, date, class, assignment, and your TA’s name.

// Fish Bear 
// 02/31/1989
// CSE 123 
// P0: Warm Up
// TA: Corn Bear

Class Comments

Class comments are comments that describe a class as a whole. The purpose of a class comment is to give a client an understanding of what a class accomplishes at a high level. As such, class comments should be present in all classes and should describe all relevant functionality of a class. Some questions to guide your thinking are what does the class do abstractly? What behaviors can an instance of the class do? Is it an interface? Does it implement an interface? Is it a subclass or superclass?

Thinking of your program as a really detailed book, the class comment would be a summary that describes things without too much detail.

Example:

// Kasey Champion
// 02/31/1989
// CSE 123
// TA: Brett Wortzman
// This class is a budgeter. It takes in monthly or daily expenses and income. It then draws
// conclusions about your spending habits.
public class Budgeter {
    // CODE HERE
}

Method Comments

Method comments are comments that describe what a method accomplishes, the inputs to the method, and the output of the method. You can think of method comments as mini-specs of a method! All method comments should include a description of the method’s behavior, the parameters of the method, and the outcomes of the method (Does it return a value? Does it manipulate a shared object?).

In CSE 123, there are two main types of acceptable commenting conventions: BERP and Pre/Post. It is your preference on which one to use on assignments. (You do not need to use both.) Each convention has its advantages and disadvantages, but both should convey the necessary method information regardless.

BERP Commenting

One helpful acronym you might hear TAs mention is BERP! It stands for:

  • Behavior - What the method does
  • Exceptions - Documenting any errors the method might raise on invalid input or state
  • Returns - What the returned value(s) are
  • Parameters - What the parameter(s) are

These are all the things that should be mentioned in a method comment if applicable. If a method doesn’t have any returns for example, that part of the comment can be omitted. Continuing the book analogy, you can think of a method comment as a chapter summary.

Pre/Post Condition Commenting

Pre-Condition: A pre-condition is a statement or expression used to inform the client about the accepted range of input. Only input that meets these criteria is guaranteed to produce a correct output. All other input (input outside the specified criteria) is not guaranteed to compute correctly.

Post-Condition: A post-condition is a statement or expression informing the client on the behavior and range of output to expect from your code.

One easy way to “translate” between BERP and Pre/Post commenting:

  • Pre-Conditions usually include discussion on valid Parameters and the Exceptions that are thrown when the input is invalid.
  • Post-Conditions usually include discussion on the overall Behavior of the method and the possible Return values.

Keep in mind that not all methods will have both a pre and post comment. Just as with BERP, some methods won’t have parameters or exceptions, so a pre-condition comment in this case is unnecessary.

Implementation Details

Something to keep in mind when you are documenting your code is to avoid implementation details. This applies to both class and method comments. For example, we don’t need to document that our method accomplishes what it does by using a loop – someone reading our code can figure that out just by looking at the method! More importantly though is that mentioning implementation details bogs down our clients. Is it important for clients to know the underlying mechanisms at play in our method? All the client really needs to know is how the method behaves which you provide insight into through your documentation. This is not an exhaustive list but implementation details include mentioning fields, looping constructs, and the data structures being created.

Private Methods

The one exception to implementation details are private methods. With private methods, it’s okay to mention implementation details since documentation for private methods is not client facing – only the implementors can see documentation for private methods. When documenting private methods, you should still follow BERP or Pre/Post and mention all necessary details for the implementors to know how the method behaves.

Comment Examples

Complete Comment Examples

BERP

// Behavior: 
//   - This method calculates net profit or loss based on monthly income and daily spending.
// Parameters:
//   - income: the user’s income this month
//   - spending: the amount the user spent each day this month
// Returns:
//   - int: the net profit or loss. Positive if profit, negative if loss.
// Exceptions:
//   - income < 0: if the given income is negative, an IllegalArgumentException is thrown.
public static int calculateNetExpenses(int income, int spending) {
    if (income < 0) {
        throw new IllegalArgumentException("Income can't be a negative integer!");
    }
    return income - (spending * DAYS_IN_MONTH);
}

Pre/Post

// Pre: accepts a int income representing the user's income and an int for user's daily spending.
//      income must be non-negative, otherwise an IllegalArgumentException is thrown.
// Post: calculates net profit or loss based on monthly income and daily spending.
//       and returns the net profit (positive) or loss (negative)
public static int calculateNetExpenses(int income, int spending) {
    if (income < 0) {
        throw new IllegalArgumentException("Income can't be a negative integer!");
    }
    return income - (spending * DAYS_IN_MONTH);
}

General

(paragraph format; neither Pre/Post or BERP, but communicates all necessary info)

// This method calculates net profit or loss based on a given monthly
// income (int) and daily spending (int). It then returns the net
// profit or loss of the user (int). An IllegalArgumentException is thrown
// if the given income is negative.
public static int calculateNetExpenses(int income, int spending) {
    if (income < 0) {
        throw new IllegalArgumentException("Income can't be a negative integer!");
    }
    return income - (spending * DAYS_IN_MONTH);
}

Incomplete Comment Examples

Missing Parameter Comments

// This method calculates net profit or loss, and returns it to the
// user. An IllegalArgumentException is thrown if the given income is negative.
public static int calculateNetExpenses(int income, int spending) {
    if (income < 0) {
        throw new IllegalArgumentException("Income can't be a negative integer!");
    }
    return income - (spending * DAYS_IN_MONTH);
}

Although this comment mentions that it calculates net profit or loss, it does not touch on the parameters of this method.

Implementation Details

// This method takes income and spending and uses the formula income -
// (spending * days in a month) to return the user’s net income.
// An IllegalArgumentException is thrown if the given income is negative.
public static int calculateNetExpenses(int income, int spending) {
    if (income < 0) {
        throw new IllegalArgumentException("Income can't be a negative integer!");
    }
    return income - (spending * DAYS_IN_MONTH);
}

This comment contains unnecessary implementation details. To get this level of granularity, clients of your code could simply look at the implementation!

Missing Return Comment and Unclear Parameter Comment

// This method calculates net profit or loss based on monthly income and daily spending.
// An IllegalArgumentException is thrown if the given income is negative.
public static int calculateNetExpenses(int income, int spending) {
    if (income < 0) {
        throw new IllegalArgumentException("Income can't be a negative integer!");
    }
    return income - (spending * DAYS_IN_MONTH);
}

This method comment is missing a return comment. Additionally, it is unclear whether income and spending are parameters as there is no indication in this comment they are user-given.

Missing Exception Comment

// This method calculates takes in an income and a spending to calculate the net profit or loss,
// and returns it to the user.
public static int calculateNetExpenses(int income, int spending) {
    if (income < 0) {
        throw new IllegalArgumentException("Income can't be a negative integer!");
    }
    return income - (spending * DAYS_IN_MONTH);
}

This comment forgets to document that an exception will be thrown if certain conditions are not met. This could throw the client off as they might not anticipate an exception being thrown.

Inline Comments

Inline comments are comments written in chunks of code. They can be in between lines of code, or at the end of them and serve to explain tricky lines or sections of code. Inline comments are great for explaining tricky lines of code. You don’t need to worry about implementation details in inline comments since they are there to explain how a piece of code works.

public static int calculateNetExpenses(int income, int spending){
    return income - spending; // This is an inline comment!!!
}