Writing Good Comments
Published: 2022-08-31 18:50:42

This is part of a brief series on [Good Habits For Java Programmers](https://dev.to/mbrubin56/good-habits-for-new-java-programmers-1n2).

## 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:
```java
/** 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.
}
```

None of these comments add anything useful. 

Because the author has used [meaningful names](https://dev.to/mbrubin56/meaningful-names-bh1) 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:
```java
    // Default constructor
    public ProfitCalculator() {
```
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
```java
    // default constructor
    public ProfitCalculator() {
        // assign buyerPrice
        this.buyerPrice = 0.0;

        // assign sellerCost
        this.sellerCost = 0.0;
    }
```
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:
```java
        // 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]);
        }
```

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](https://dev.to/mbrubin56/meaningful-names-bh1).

## 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.