Topic 1.8 — Documentation with Comments

Goal: explain why documentation matters, write clear comments, and distinguish helpful comments from “noise.”

The big idea

Comments are notes for humans. They don’t change what the program does, but they make code easier to understand, maintain, and debug.

In CSA, good documentation helps you (and others) read code quickly and avoid mistakes.

What comments are (and aren’t)

  • Comments are ignored by the compiler.
  • They can explain purpose, logic, and assumptions.
  • They should not be used to “hide” messy code—clean code + clear comments is the goal.

Two common comment styles in Java

// Single-line comment

/*
  Multi-line comment
*/

You’ll also see documentation-style comments (Javadoc) later, but basic comments are enough for Unit 1.

Golden rule

Comment the why more than the what. (The code already shows “what” most of the time.)

Good vs. bad comments (examples)

Helpful comments

// Track the highest score seen so far
int maxScore = 0;

// Convert inches to centimeters (1 in = 2.54 cm)
double cm = inches * 2.54;

These explain purpose or meaning, not obvious syntax.

Unhelpful / noisy comments

// set x to 5
int x = 5;

// add 1 to x
x = x + 1;

The code already says this. These comments don’t add understanding.

Where to place comments

  • At the top of a file/class to describe what it is for.
  • Before a tricky block of code to explain what the block accomplishes.
  • Near a “gotcha” or assumption to prevent mistakes.

Example: documenting a short program

Same code, but more readable with purpose-focused comments.

public class ScoreDemo {
  public static void main(String[] args) {
    // Start with a base score
    int score = 10;

    // Apply bonus points for a task completion
    score += 5;

    // score now represents the final points earned
  }
}

Common mistakes

  • Comments that are incorrect or outdated (worse than no comments).
  • Commenting every single line (makes code harder to read).
  • Using comments instead of meaningful variable names.

How to write better comments

  • Use clear variable names first.
  • Write comments for the overall goal of a block.
  • Explain assumptions (units, ranges, meanings).
  • Keep comments short and accurate.

Quick self-check

  1. Do comments affect what the program does?
  2. What should comments explain more: “what” or “why”?
  3. Give one example of a helpful comment.
  4. Why are outdated comments dangerous?
  5. What’s one way to reduce the need for comments?

← Back to Unit 1 topics