Documenting APIs and Public Interfaces
You'll learn how to write clear, complete documentation for public methods so others (and future-you) know exactly how to use them without reading implementation details.
Why API Documentation Matters
When you expose a public method, class, or interface, you're making a contract with other developers. They shouldn't need to dig through your implementation to understand what a function does, what it expects, or what it returns. Think of API documentation as the instruction manual that comes with a product—without it, users are left guessing.
What to Document
For every public method or function, document these elements clearly:
1. Purpose — What does this method do? Be concise but complete.
2. Parameters — What does each parameter mean? What types are valid? Are there constraints (e.g., "must be positive")?
3. Return Values — What does the method return? Under what conditions might it return different values?
4. Exceptions — What errors might this method throw and why? This helps callers handle failures properly.
5. Side Effects — Does it modify state, write to a file, or change a global? Make it explicit.
Example Documentation Style
/**
* Calculates the total price including tax.
*
* @param basePrice The item price before tax (must be >= 0)
* @param taxRate The tax rate as a decimal (e.g., 0.08 for 8%)
* @return The total price including tax, rounded to two decimals
* @throws IllegalArgumentException if basePrice is negative
*/
This tells users everything they need without looking at the code inside.
Keep It Updated
Documentation rots quickly. When you refactor a method, update its documentation immediately. Outdated docs are worse than no docs—they mislead.
Key Takeaway: Comprehensive API documentation answers what, why, inputs, outputs, and exceptions—making your code usable without requiring anyone to reverse-engineer your implementation.