UNIT 1.8
Documentation with Comments
AP Computer Science A
Using Objects and Methods
Learning Objective 1.8.A
Describe the functionality and use of code through comments.
What are Comments?
- Help programmers understand code and its functionality
- Are ignored by the compiler
- Are not executed when the program runs
- Serve as documentation for both original and future programmers
Key Point: Comments are for humans to read, not for the computer to execute!
Three Types of Comments in Java
2. Multi-Line Comments: /* */
Creates a block of comments spanning multiple lines
3. Javadoc Comments: /** */
Used to create API documentation
Comment Examples in Practice
Preconditions
Important: There is no expectation that the method will check to ensure preconditions are satisfied.
Example:
The method assumes the caller will pass a non-negative value.
Postconditions
Postconditions describe the outcome of execution in terms of:
- What is being returned
- The current value of object attributes
Example:
Comment Best Practices
DO:
- Explain why code exists
- Document complex algorithms
- Specify preconditions and postconditions
- Keep comments up-to-date
- Use Javadoc for public methods
DON'T:
- State the obvious
- Write comments that repeat code
- Leave outdated comments
- Use comments to fix bad code
- Write novels in comments
Remember: Good code should be self-documenting, with comments adding valuable context!
Good vs. Bad Comments
Bad Comments
These comments just repeat what the code already says!
Good Comments
These comments explain the purpose and context!
Unit 1.8 Summary
Key Takeaways:
- Comments document code for human readers, not computers
- Three types: // (single-line), /* */ (multi-line), /** */ (Javadoc)
- Preconditions: What must be true before method execution
- Postconditions: What must be true after method execution
Essential Knowledge 1.8.A: Use comments to describe functionality, document preconditions and postconditions, and help other programmers understand your code.
Good documentation makes good programmers!
1. Single-Line Comments: //
Creates a comment on one line