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: Rilakkuma

Commenting Guidelines

Do not plagiarize

Your comments should be written in your own words. You should not directly copy-and-paste any text from the spec. We want to see if you understand how to write good comments, not how good you are at copying-and-pasting. It’s OK to be inspired by the spec, borrow certain phrases from it, and use it to remind you on things to comment on, but you should never copy it wholesale.

Know your audience

When commenting your classes and methods, be sure to keep in mind who exactly your comments are addressed to. You should assume that your reader is competent, does not know anything about the assignment, and does not care about how your code works, only what it does.

More about knowing your audience

Like any form of writing, it’s very important to know who exactly your audience is before starting. That way, you know what sort of tone you should be taking, what kind of information is relevant, and what sorts of things to focus on.

Because we want you to get practice in how to write high-quality comments (the kind that other professional programmers would expect), we want you to assume that whoever will be reading your comments fits the following profile:

Assume your readers are competent programmers.

That means you should not spend the time explaining how things like a for loop or a println works. Assume that your reader is already familiar with Java to a reasonable extent.

Assume your readers know nothing about the specification.

You should assume that your reader knows nothing about the specification, what it is, what it’s supposed to do, and why your implementation exists (perhaps they didn’t take classes at UW). They just need to understand how to interact with your code.

Assume your readers don’t care about how exactly your code works, only how to use it.

We will revisit and elaborate on this assumption in CSE 123, but for now, you should assume that whoever is reading your method header comments is doing so because they need to interact with your code in some way. That means you should spend a lot of time elaborating on what your parameters are (and what values are acceptable), and what effect calling that method has/what values you’ll return.

However, they don’t care how precisely that method works, whether you’re using a print or println or anything to that effect.

Note: This point only applies to method header comments, NOT to inline comments (comments inside a method). If somebody is reading your inline comments, that means that they are interested in how exactly your method works. In that case, this assumption wouldn’t apply.

Implementation Details

Your public class and method comments should never include implementation detail – information about how exactly the method or class works.

One useful way of determining if something would count as implementation detail is to ask yourself if your code would survive a total internal rewrite. If it doesn’t, odds are it contains implementation detail.

More about implementation details

When commenting, you should try and write comments that are robust and focus on describing the contract or promise between the caller and the implementor: preconditions and postconditions. They should not mention how exactly that contract is fulfilled (that way, the implementor is free to change their mind about how exactly to go about writing a method without ever bothering the client).

A useful rule of thumb is to ask yourself if your comments would survive a total internal rewrite. More specifically, imagine that somebody took the homework spec, and produced a program that has full external correctness, but decided to make the class internally completely crazy. They used advanced material, crazy data structures, a completely different programming language, horrible style, etc…

Because both the twisted version and the normal version of the assignment both have full external correctness, and behave completely identically from the perspective of the client, you should be able to take your comments, copy-and-paste them into the twisted program, and still have the comments perfectly and accurately describe the behavior of the twisted program. Their internal behavior might be completely different, but they’re identical externally, so your comments should apply to both versions.

For example, consider how this comment works for all these different types of implementations for a method that finds the sum of all the numbers inside of an ArrayIntList class.

// Returns the sum of all numbers in the ArrayIntList.
public int sum() {
    int output = 0;
    for (int i = 0; i < this.size; i++) {
        output += this.elementData[i];
    }
    return output;
}

// Returns the sum of all numbers in the ArrayIntList.
public int sum() {
    int output = 0;
    for (int i = 0; i < this.length; i++) {
        output += this.data[i];
    }
    return output;
}

// Returns the sum of all numbers in the ArrayIntList.
public int sum() {
    int output = 0;
    int i = 0;
    while (i < this.length) {
        output += this.data[i];
        i += 1;
    }
    return output;
}

// Returns the sum of all numbers in the ArrayIntList.
public int sum() {
    int output = 0;
    for (int num : this.data) {
        output += num;
    }
    return output;
}

// Returns the sum of all numbers in the ArrayIntList.
public int sum() {
    return this.data.stream().limit(this.size).sum();
}

// Returns the sum of all numbers in the ArrayIntList.
public int sum() {
    return this.totalSum;
}

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 mention all necessary details for the implementors to know how the method behaves.

Assumptions about the client

Your comments should never make any assumptions about the behavior of the client.

More about assumptions about the client

This principle is the inverse of implementation detail: your comments should not expose internal detail, and should not speculate on external detail. That is because your class should be flexible enough to be reused by a theoretically infinite number of clients, and it’s silly to bind your class to a specific client.

Again, comments document the boundary between client and implementation. You should never mention either of the two, and restrict yourself to only talking about that boundary and interface between the two.

For example, the following would be an example of a bad comment – it assumes that the Scanner object is reading from a file:

// Reads in a sequence of lines from a file, and stores them in a list
public List<String> readFile(Scanner input) {
    List<String> output = new LinkedList<String>();
    while (input.hasNextLine()) {
        output.add(input.nextLine());
    }
    return output;
}

This would be another example of a bad comment, since it mentions a specific client by name:

// Represents a chunk of arbitrary text as a sequence of characters for a guessing game 
// program
public class String {
    // ..snip..
}
You should assume that a potentially infinite number of clients may choose to use your particular object for any arbitrary reason. Consequently, you should not “hard-code” in references to specific clients into your comments.

Comment every class and method you implement

You must comment every class you implement. You must comment every single method in your class. Your comment should describe what that class/method does (but not how it does it).

Note: The exception to this rule is your public static void main(String[] args) method.

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 either.) What is important is that every comment conveys the necessary method information. Each convention has its advantages and disadvantages, but both should accomplish that goal.

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.

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.

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!!!
}