Documentation with Comments
Why this matters
Imagine you and your friend Marcus are building a massive, custom PC. You spend a weekend carefully routing cables, installing components, and tweaking settings. You label a few key cables with masking tape. A month later, Marcus wants to upgrade the graphics card, but you’re away at a debate tournament. Without your notes, he’s lost. Which cable goes where? What was that specific setting you used in the BIOS? The project grinds to a halt.
Code is the same way. When you write a program, you're not just giving instructions to a computer; you're leaving a blueprint for other people (and your future self!). Comments are the labels and notes in that blueprint. They explain the why behind your code, making it understandable, maintainable, and less of a headache to revisit weeks or months later.
Today, we'll learn how to write effective comments and use them to create clear "contracts" for our methods.
Concept overview
flowchart TD
A[Start: Programmer wants to call a method] --> B{Are all preconditions met?};
B -- Yes --> C[Call the method];
C --> D[Method code executes];
D --> E[Postconditions are now true];
E --> F[End];
B -- No --> G[Do not call the method, or expect undefined behavior];
G --> F;
Core explanation
Welcome to one of the most important habits of a professional programmer: documenting your code. It might not seem as exciting as writing a cool new feature, but trust me, it's a skill that will save you and your teammates countless hours of frustration.
Why Bother with Comments?
Code is read far more often than it is written. You might write a method once, but you, your classmates, or your future colleagues might read it dozens of times. Comments are notes you leave inside your source code that are completely ignored by the compiler. They don't run, they don't slow your program down, and they have zero effect on the output. Their only purpose is to help humans understand what's going on.
Think of it like a recipe. The code is the list of ingredients and the step-by-step instructions. The comments are the helpful notes you'd scribble in the margin: "Use a non-stick pan for easier cleanup!" or "Chill the dough for at least an hour for best results." The notes don't change the recipe, but they make it much easier to follow and get a great result.
The Three Types of Java Comments
Java gives us three ways to write comments.
-
Single-Line Comments:
//This is your go-to for short, quick notes. Anything after the//on the same line is a comment.double price = 100.0; double salesTax = 0.0825; // Using the sales tax for Dallas, TX double finalPrice = price * (1 + salesTax); -
Multi-Line (Block) Comments:
/* ... */When you need more space, you can use a block comment. It starts with/*and ends with*/. Everything in between is ignored. These are great for longer explanations or for temporarily "commenting out" a chunk of code while you're testing something else./* This block of code calculates the final price of an item. We are assuming a standard item and not accounting for any special discounts or tax-exempt statuses. The tax rate is hard-coded for now. */ double price = 100.0; double salesTax = 0.0825; double finalPrice = price * (1 + salesTax); -
Javadoc Comments: `/ ... */
** This is the professional standard. Javadoc comments look similar to block comments but start with/**`. They are special because a tool called Javadoc can read them and automatically generate clean, professional-looking documentation for your code (an API). This is how the official Java documentation you'll look up all year is made!
```java
/**
* Calculates the final price of an item including sales tax.
* @param price The initial price of the item before tax.
* @param taxRate The sales tax rate as a decimal (e.g., 0.0825 for 8.25%).
* @return The final price including tax.
*/
public double calculateFinalPrice(double price, double taxRate) {
return price * (1 + taxRate);
}
```
Notice the `@param` and `@return` tags. These are special Javadoc tags that clearly identify the method's parameters and what it returns.
The Method Contract: Preconditions and Postconditions
Now for two of the most important concepts in documentation: preconditions and postconditions. Think of them as a contract between the person who writes a method and the person who calls it.
This is where many students get stuck, so let's use an analogy. Imagine a gumball machine.
- PreconditionYou must insert a quarter ($0.25). This is a condition that must be true before you can use the machine. The machine assumes you will do this. It doesn't check your pockets for a quarter beforehand.
- PostconditionA gumball is dispensed. This is the condition that is guaranteed to be true after you've successfully used the machine (i.e., met the precondition).
In code, it's the same idea:
Preconditions
A precondition is a condition that must be true before a method is called for it to work correctly. It's a rule for the caller of the method.
For our calculateFinalPrice method, a precondition would be that price and taxRate cannot be negative. The method assumes it will receive valid inputs.
This is the critical part: The method itself is not expected to check if the precondition is true. The responsibility is on the programmer using the method to provide valid data. If you call the method with a negative price, its behavior is undefined—it might crash, it might return a weird number, but it's not the method's fault, because the contract was broken.
Postconditions
A postcondition is a condition that is guaranteed to be true after the method has finished running (assuming the preconditions were met). It describes the outcome.
For calculateFinalPrice, the postcondition is that the method returns a double value representing the original price plus the calculated tax. It could also describe a change to an object's state. For example, if a withdraw method is called on a BankAccount object, a postcondition would be that the account's balance has been reduced.
Pre- and postconditions are typically written inside a Javadoc comment block to make the "contract" crystal clear.
/**
* Calculates the final price of an item including sales tax.
*
* PRECONDITION: price >= 0 and taxRate >= 0.
* POSTCONDITION: Returns the price including tax.
*
* @param price The initial price of the item before tax.
* @param taxRate The sales tax rate as a decimal.
* @return The final price including tax.
*/
public double calculateFinalPrice(double price, double taxRate) {
return price * (1 + taxRate);
}
By documenting your code this way, you make it robust, predictable, and easy for others to use correctly.
See it in action
Worked examples
Let's walk through how to apply these documentation concepts in practice.
Example 1: Documenting a Player's Score Update
Problem: You're creating a Player class for a game. You have a method increaseScore that adds points to the player's total score. Write the complete Javadoc documentation for this method, including pre- and postconditions.
Solution Walkthrough:
- 1Identify the GoalThe method
increaseScoretakes an integerpointsand adds it to the player'scurrentScore. - 2Think About the "Contract"
- PreconditionWhat must be true for this to make sense? We probably shouldn't be able to add negative points with this method; that should be a different method like
decreaseScore. So, a good precondition is thatpointsmust be a non-negative number. - PostconditionWhat happens after the method runs? The player's
currentScorewill have been increased by thepointsvalue. The method doesn't return anything (void), so the postcondition is all about the change in the object's state.
- Precondition
- 3Write the JavadocWe'll use a
/** ... */block. We'll state the purpose, list the pre- and postconditions, and use the@paramtag to describe thepointsparameter.
public class Player {
private int currentScore;
private String username;
// ... constructor and other methods ...
/**
* Increases the player's score by a given number of points.
*
* PRECONDITION: points >= 0
* POSTCONDITION: this.currentScore is increased by the value of points.
*
* @param points The non-negative number of points to add to the score.
*/
public void increaseScore(int points) {
// The method assumes the precondition is met.
// It does not check if points is negative.
this.currentScore += points;
}
}
- What the method does: "Increases the player's score."
- The rule she must follow: "I must pass in a non-negative number of points." (Precondition)
- The guaranteed result: "The player's score will go up." (Postcondition)
Example 2: Documenting a Circle's Area Calculation
Problem: You have a Circle class with a method to calculate its area. The radius is stored as an instance variable. Document the getArea method.
Solution Walkthrough:
- 1Identify the GoalThe
getAreamethod calculates and returns the area of the circle using the formula A = πr². - 2Think About the "Contract"
- PreconditionDoes this method take any parameters? No. So the precondition must be about the state of the
Circleobject itself. For the area to be valid, the circle'sradiusmust have been initialized to a non-negative value. - PostconditionWhat is the result? The method will return a
doublethat is the calculated area of the circle. The state of theCircleobject itself (its radius) does not change.
- Precondition
- 3Write the Javadoc
public class Circle {
private double radius;
/**
* Constructs a new Circle with a given radius.
* @param initialRadius The radius of the circle.
*/
public Circle(double initialRadius) {
this.radius = initialRadius;
}
/**
* Calculates the area of the circle.
*
* PRECONDITION: The circle's radius is >= 0.
* POSTCONDITION: Returns the calculated area of the circle.
*
* @return The area of the circle as a double.
*/
public double getArea() {
// Math.PI is a built-in constant for pi
return Math.PI * this.radius * this.radius;
}
}
Try it yourself
Time to practice your documentation skills.
- 1Rectangle AreaBelow is a method that calculates the area of a rectangle. Write a complete Javadoc comment block for it. Include
@paramtags, an@returntag, and appropriate pre- and postconditions.public double getRectangleArea(double length, double width) { return length * width; }Hint: What must be true about
lengthandwidthbefore the method is called? What does the method promise to return? - 2Class RosterImagine a method
addStudent(Student newStudent)for aCourseobject. The course has a maximum capacity of 30 students. Identify a key precondition and postcondition for this method. You don't need to write the code, just the pre- and postcondition statements. Hint: Think about the state of theCourseobject. What must be true about the roster before you can add a student? What is true about the roster after a student has been successfully added?
Practice — 8 questions
In simple terms, comments are notes in your code for humans to read. They explain what the code does, but the computer completely ignores them when running the program.
double price = 100.0;
double salesTax = 0.0825; // Using the sales tax for Dallas, TX
double finalPrice = price * (1 + salesTax);
```
2. **Multi-Line (Block) Comments: `/* ... */`**
When you need more space, you can use a block comment. It starts with `/*` and ends with `*/`. Everything in between is ignored. These are great for longer explanations or for temporarily "commenting out" a chunk of code while you're testing something else.
```java
/*
This block of code calculates the final price of an item.
We are assuming a standard item and not accounting for
any special discounts or tax-exempt statuses.
The tax rate is hard-coded for now.
*/
double price = 100.0;
double salesTax = 0.0825;
double finalPrice = price * (1 + salesTax);
```
3. **Javadoc Comments: `/** ... */`**
This is the professional standard. Javadoc comments look similar to block comments but start with `/**`. They are special because a tool called Javadoc can read them and automatically generate clean, professional-looking documentation for your code (an API). This is how the official Java documentation you'll look up all year is made!
[[fig:javadoc_vs_block]]
```java
/**
* Calculates the final price of an item including sales tax.
* @param price The initial price of the item before tax.
* @param taxRate The sales tax rate as a decimal (e.g., 0.0825 for 8.25%).
* @return The final price including tax.
*/
public double calculateFinalPrice(double price, double taxRate) {
return price * (1 + taxRate);
}
```
Notice the `@param` and `@return` tags. These are special Javadoc tags that clearly identify the method's parameters and what it returns.
### The Method Contract: Preconditions and Postconditions
Now for two of the most important concepts in documentation: **preconditions** and **postconditions**. Think of them as a contract between the person who *writes* a method and the person who *calls* it.
This is where many students get stuck, so let's use an analogy. Imagine a gumball machine.
* **Precondition:** You must insert a quarter ($0.25). This is a condition that must be true *before* you can use the machine. The machine *assumes* you will do this. It doesn't check your pockets for a quarter beforehand.
* **Postcondition:** A gumball is dispensed. This is the condition that is guaranteed to be true *after* you've successfully used the machine (i.e., met the precondition).
In code, it's the same idea:
#### Preconditions
A **precondition** is a condition that must be true *before* a method is called for it to work correctly. It's a rule for the *caller* of the method.
For our `calculateFinalPrice` method, a precondition would be that `price` and `taxRate` cannot be negative. The method assumes it will receive valid inputs.
**This is the critical part:** The method itself is not expected to check if the precondition is true. The responsibility is on the programmer using the method to provide valid data. If you call the method with a negative price, its behavior is undefined—it might crash, it might return a weird number, but it's not the method's fault, because the contract was broken.
#### Postconditions
A **postcondition** is a condition that is guaranteed to be true *after* the method has finished running (assuming the preconditions were met). It describes the outcome.
For `calculateFinalPrice`, the postcondition is that the method returns a `double` value representing the original price plus the calculated tax. It could also describe a change to an object's state. For example, if a `withdraw` method is called on a `BankAccount` object, a postcondition would be that the account's balance has been reduced.
Pre- and postconditions are typically written inside a Javadoc comment block to make the "contract" crystal clear.
- 1.8.A: Describe the functionality and use of code through comments.
- 1.8.A.1
- Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run. Three types of comments in Java include /* */, which generates a block of comments; //, which generates a comment on one line; and /** */, which are Javadoc comments and are used to create API documentation.
- 1.8.A.2
- A precondition is a condition that must be true just prior to the execution of a method in order for it to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
- 1.8.A.3
- A postcondition is a condition that must always be true after the execution of a method. Postconditions describe the outcome of the execution in terms of what is being returned or the current value of the attributes of an object.
flowchart TD
A[Start: Programmer wants to call a method] --> B{Are all preconditions met?};
B -- Yes --> C[Call the method];
C --> D[Method code executes];
D --> E[Postconditions are now true];
E --> F[End];
B -- No --> G[Do not call the method, or expect undefined behavior];
G --> F;
Read what Saavi narrates
(gentle, warm intro music fades)
Hey everyone, it's Saavi. Let's talk about something that separates good programmers from great ones: writing clear notes in your code.
Imagine you and a friend are building a complicated model airplane. You spend a whole day on it, but have to leave it half-finished. If you don't leave any notes, coming back to it a month later will be a nightmare. Which part goes where? Why did you use that specific type of glue?
Code is exactly the same. The notes you leave for yourself and others are called comments. They're ignored by the computer, but they're essential for humans.
Essentially, comments are notes that explain your code's purpose. We're also going to learn about two special kinds of comments, preconditions and postconditions, that act like a contract for your code, making it predictable and reliable.
Let's look at a quick example. Imagine a method that calculates the final price of an item, including sales tax. In our Javadoc, which is the formal documentation, we would describe what it does. We'd use a tag called at-param to describe the input, say, the item's price. And we'd use an at-return tag to describe the output, which is the final price.
But here's the important part: the contract. The precondition is what must be true *before* someone uses our method. For our price calculator, a precondition would be that the price can't be negative. The postcondition is what we guarantee will be true *after* the method runs. In this case, it will return the correct final price.
Now, here’s a really common mistake. Students often think the method is supposed to *check* for the precondition. For example, they'll write a precondition that the price must be positive, and then write an if-statement inside the method to check if the price is positive. But that's not the point of a precondition! A precondition is a rule for the person *calling* the method. The method itself just assumes the rule will be followed. It's a matter of responsibility. The caller is responsible for providing good data, and the method is responsible for producing the right result with that data.
Mastering comments, especially preconditions and postconditions, will make your code so much easier to work with. It's a habit that pays off for your entire programming journey. Keep up the great work, and I'll see you in the next lesson.
(gentle, warm outro music fades in)
This adds no new information. Anyone who can read Java knows what `score++` does. Comments should explain the *why*, not the *what*.
Explain the reason for the code. `score++; // Add a point for completing the level.`
A precondition is an assumption the method makes about its inputs; it's a rule for the *caller*. The method itself is not required to verify it. While defensive programming (checking inputs) is a good practice, it's a separate concept from a precondition contract.
State the precondition in the Javadoc. Trust that the caller will follow the rule. The method's code should proceed assuming the input is valid.
The compiler will treat everything after the opening `/*` as a comment until it finds a `*/`. This can cause huge, confusing chunks of your code to be accidentally ignored.
Always type the opening `/*` and closing `*/` at the same time, then fill in the middle. Many code editors do this for you automatically.
This describes *how* the area is calculated, not *what* the result represents. If you later change the implementation (the "how"), you'd have to update your comment, which is easy to forget.
Describe the outcome or the state change. `POSTCONDITION: Returns the area of the triangle.`
The compiler completely strips out all comments before the program is executed. They have zero impact on performance or the size of the final executable program.
Comment your code generously. The benefits for human understanding far outweigh the non-existent performance cost.