DEV Community

Mark Rubin
Mark Rubin

Posted on • Updated on

Writing Good Comments

This is part of a brief series on Good Habits For Java Programmers.

Don't narrate your code

Many beginning Java programmers have been taught to make sure to include comments in their programs. And because they are good, dutiful students, they do. A great deal of this time, those comments are simply narrations of their code, and so are unnecessary. Here are some examples in an abbreviated class:

/** Calculates profit. */
public class ProfitCalculator {
    private double buyerPrice; // the buyer's price
    private double sellerCost; // the seller's cost

    // default constructor
    public ProfitCalculator() {
        // assign buyerPrice
        this.buyerPrice = 0.0;

        // assign sellerCost
        this.sellerCost = 0.0;
    }

    public ProfitCalculator(double buyerPrice, double sellerCost) {
        // Save the buyer price in a member field.
        this.buyerPrice = buyerPrice;

        // Save the seller cost in a member field.
        this.sellerCost = sellerCost;
    }

    // Sets the buyer price.
    public void setBuyerPrice(double buyerPrice) {
        this.buyerPrice = buyerPrice;
    }

    // More code would follow.
}
Enter fullscreen mode Exit fullscreen mode

None of these comments add anything useful.

Because the author has used meaningful names for the variables and methods, the comment here
private double buyerPrice; // the buyer's price
doesn't add anything and isn't needed.

A method with the signature
public void setBuyerPrice(double buyerPrice)
had better set the buyer price! So a comment telling us that isn't needed, or else the author ought to rename their method and their parameter!

Let's look at this one:

    // Default constructor
    public ProfitCalculator() {
Enter fullscreen mode Exit fullscreen mode

This is interesting because texts that are teaching students what a default constructor is will often have a comment just like that on their examples of default constructors. That's helpful to you as a student. And so it's totally natural that you would mimic the example from your texts. But the programs you're mimicking are intended to teach you what a default constructor is; the programs you're writing are not meant to be examples to teach others how to code, and so you shouldn't include comments as if they were. Which means not mimicking your examples in this way.

This leads to a bit of a tricky situation for students. Maybe you think it's still useful to add to your default constructor // default constructor because it's helpful to you as you're starting out. I'm torn here: I like that you're adding comments that you think are genuinely helpful and are genuinely helpful to you. But we can assume that the readers of our code know basic Java, and so don't need default constructors and other standard bits of Java highlighted for them unless for some reason, it would be tricky to see those things without your comment.

Another example

    // default constructor
    public ProfitCalculator() {
        // assign buyerPrice
        this.buyerPrice = 0.0;

        // assign sellerCost
        this.sellerCost = 0.0;
    }
Enter fullscreen mode Exit fullscreen mode

Anyone familiar with Java will know that those lines in the body of the constructor are assignment statements and what variables the assignments are being made to. So it's not helpful to add those comments.

So what comments should I include?

I'm going to be pretty heretical here. If you have used meaningful names for your classes, variables, methods, parameters, and so on, maybe very few! Ideally, the code is self-documenting because it's obvious from the names of things and the flow of your statements what the program is doing and why. Especially for the size of the programs you're writing.

Less heretically, any time your program does anything important that a reader might not pick up on right away, that deserves a comment. What's wrong with the comments in the previous section is that they focus too much on what the code does rather than on why it does it. The what is often not a problem for fluent Java readers. It's when they may not understand why your code does what it does that they may need help.

So if you, for example, skip a line of input from a file or an element of an array for some reason, you should comment that:

        // We need to skip printing the first price because
        // it has already been printed in <some other place>, 
        // so we start iterating at 1.
        for (int i = 1; i < prices.length; ++i) {
            System.out.println(prices[i]);
        }
Enter fullscreen mode Exit fullscreen mode

And it's good advice to have a top-level comment on your program saying what the program does in general and any interesting facts about it. And it's generally good advice to think about putting a top-level comment on your classes, describing what the classes do and how they work, although the same principles apply here, too, about making sure you're adding something meaningful in your comment: if it's totally obvious what a ProfitCalculator class does, perhaps a comment isn't necessary.

So some fellow instructors may dislike this advice because instructors are generally pleading with their students to add comments. I also plead with you to add comments, but when they are necessary and meaningful. I'm pleading with you not to add comments that add no real value. And I'll plead with you even harder to use meaningful names.

Grammar

Comments should be grammatical

Comments are there to help you and especially your readers. If they are ungrammatical, they add a mental tax to you and your readers; poor grammar makes it harder to figure out what was meant. Not everyone is good at grammar, and that's okay. Do your best, but do try.

Comments should not contain abbreviations

This is a bit of a hot take, but don't abbreviate where elaboration would be clearer, except when using very standardly abbreviated terms, such as e.g. and etc.. So rather than say
// Calc the profit.
say
// Calculate the profit.

Comments should be complete sentences that end with periods.

This is absolutely a hot take, and definitely most developers don't do this. I learned to push for this from a peer, and I love it. Again, comments are meant to be helpful. Complete sentences are generally more helpful than not. And deciding on writing a complete sentence (and removing abbreviations) eliminates the question for you of how non-standard your English is allowed to be. Just write a complete, grammatical sentence with full words, and you and your code readers will be grateful when reading them, and you won't have to debate in your head if your sentence fragment with abbreviations is understandable. It makes programming easier for you to write your comments well and consistently because now you have a simple rule.

Top comments (0)