Documentation with Comments and Preconditions
Three Kinds of Comments
// single-line comment
/* multi-line
comment */
/** a documentation comment — describes a class or method for other programmers */
The compiler ignores all three completely — they exist for whoever reads the code next, including future-you.
Preconditions and Postconditions
A precondition is what has to be true before a method is called for it to work correctly. A postcondition is what's guaranteed true after it runs.
/**
* @param targetRPM the speed to spin up to
* Precondition: targetRPM is between 0 and the motor's max RPM.
* Postcondition: the motor ramps toward targetRPM.
*/
public void spinUpTo(double targetRPM) { ... }
Java doesn't enforce preconditions automatically — nothing stops you from calling spinUpTo(-500). A precondition is a documented expectation, not a guarantee the method checks it. Math.sqrt(-4) is a real example: nothing crashes, but the result is NaN ("not a number") because negative input violates sqrt's precondition.
Why Bother Documenting This
Once you write a method, other people (including future-you, and your whole team) will call it without reading its implementation. Documenting preconditions and postconditions is how they know what's safe to pass in and what to expect back — without documentation, the only way to find out is to read the method's full source or guess.
Common Pitfalls
- Assuming a precondition is enforced. Documenting a precondition doesn't make Java check it — passing a bad value can still silently produce a wrong result (like
NaN) instead of an error. - Skipping documentation on methods other people will call. The cost of a two-line comment is much smaller than the cost of a teammate guessing wrong about what a method expects.
Key Takeaways
//,/* */, and/** */are the three comment styles; the compiler ignores all of them.- A precondition is what must be true before a method is called; a postcondition is what's guaranteed true after it returns.
- Preconditions are documented expectations, not automatically enforced — violating one can produce a wrong result without an error.
Derived from csawesome-2026: unit-1-using-objects-and-methods/1.08-documentation-with-comments-and-preconditions.md (CSA 1.8)