Documentation Standards
Why Documentation Matters
Good documentation is the difference between a project people can actually use and one that sits abandoned in a GitHub repo. It’s how you help future contributors (including future you) understand what you built and why.
Here’s the reality: Code without documentation is like a puzzle with missing pieces. You might figure it out eventually, but it’s frustrating and wastes time. Good docs make your project accessible, maintainable, and actually useful to others.
Think of documentation as a gift to your future self. Six months from now, you won’t remember why you made certain decisions. Document now, thank yourself later.
The Documentation Hierarchy
Different types of documentation serve different purposes. Here’s what you need and when:
1. Code Comments (Inline Documentation)
Purpose: Explain why code does something, not what it does.
The code itself should be self-explanatory through good naming and structure. Comments add context that isn’t obvious from reading the code.
When to comment:
// Good - explains reasoning
// Using binary search because dataset can be 10k+ items
const index = binarySearch(items, target);
// Good - documents a workaround
// Safari doesn't support lookbehind regex, so we use this approach
// TODO: Simplify when Safari adds support (https://bugs.webkit.org/show_bug.cgi?id=174931)
const result = alternativeApproach(text);
// Good - clarifies complex logic
// Calculate compound interest: A = P(1 + r/n)^(nt)
const amount = principal * Math.pow(1 + rate / frequency, frequency * years);When NOT to comment:
// Bad - states the obvious
// Increment counter
counter++;
// Bad - restates the code
// Check if user is admin
if (user.role === 'admin') {Red flags that your code needs better names, not comments:
- You’re explaining what a variable holds
- You’re describing what a function does
- You’re clarifying control flow that’s already visible
Fix the code instead:
// Bad
let d = 86400; // seconds in a day
// Good
const SECONDS_PER_DAY = 86400;2. Function/Method Documentation
Purpose: Describe what a function does, its parameters, return value, and any important behavior.
For JavaScript/TypeScript - Use JSDoc:
/**
* Calculate the total price including tax and shipping.
*
* @param {number} subtotal - Price before tax and shipping
* @param {number} taxRate - Tax rate as a decimal (e.g., 0.08 for 8%)
* @param {number} shippingCost - Flat shipping cost
* @returns {number} Total price including all fees
* @throws {Error} If subtotal is negative
*
* @example
* calculateTotal(100, 0.08, 10); // Returns 118
*/
function calculateTotal(subtotal, taxRate, shippingCost) {
if (subtotal < 0) {
throw new Error('Subtotal cannot be negative');
}
return subtotal * (1 + taxRate) + shippingCost;
}For Python - Use docstrings:
def calculate_total(subtotal: float, tax_rate: float, shipping_cost: float) -> float:
"""
Calculate the total price including tax and shipping.
Args:
subtotal: Price before tax and shipping
tax_rate: Tax rate as a decimal (e.g., 0.08 for 8%)
shipping_cost: Flat shipping cost
Returns:
Total price including all fees
Raises:
ValueError: If subtotal is negative
Example:
>>> calculate_total(100, 0.08, 10)
118.0
"""
if subtotal < 0:
raise ValueError('Subtotal cannot be negative')
return subtotal * (1 + tax_rate) + shipping_costFor other languages:
- Java: JavaDoc
- Rust: Doc comments (
///) - Go: Standard comments above functions
- C++: Doxygen
What to include:
- Brief description of what the function does
- Parameters and their types/constraints
- Return value and its type
- Exceptions/errors that might be thrown
- Side effects (modifies external state, makes API calls, etc.)
- Examples for complex functions
What to skip:
- Obvious functions with self-explanatory names
- Private helper functions that are only used internally
- Getters/setters with no special logic
3. README Documentation
Purpose: First thing people see. Should get them from zero to running your project quickly.
Every project MUST have a README with these sections:
Minimal README Template
# Project Name
One-sentence description of what this project does.
## What It Does
2-3 paragraphs explaining:
- The problem this solves
- Main features
- Who might use this
## Quick Start
### Prerequisites
- List dependencies (Node.js 18+, Python 3.9+, etc.)
- Any accounts needed (API keys, database access)
### Installation
Step-by-step commands to get it running:
```bash
git clone https://github.com/seadclub/project-name.git
cd project-name
npm install
cp .env.example .env
# Edit .env with your settings
npm startShould be running at http://localhost:3000
Usage
Basic examples of how to use the project:
# Example commands
npm run build
npm testProject Structure
src/
├── components/ # React components
├── utils/ # Helper functions
└── api/ # API routesBrief explanation of key directories.
Configuration
Explain important environment variables or config options:
DATABASE_URL- PostgreSQL connection stringAPI_KEY- Third-party API key (get from…)
Contributing
Link to CONTRIBUTING.md or explain how to contribute:
- Fork the repo
- Create a feature branch
- Make your changes
- Submit a pull request
See issues tagged “good first issue” for places to start.
License
[MIT/Apache 2.0/etc.]
Contact
Questions? Reach out in our Telegram or open an issue.
#### Advanced README Elements
For larger projects, consider adding:
**Screenshots/Demo:**
```markdown
## Demo

Or link to a live demo: [demo.example.com](https://demo.example.com)Roadmap:
## Roadmap
- [x] User authentication
- [x] Basic CRUD operations
- [ ] Real-time updates
- [ ] Mobile appTroubleshooting:
## Common Issues
**Port already in use:**
Change the port in `.env` or kill the existing process:
`lsof -ti:3000 | xargs kill`
**Database connection fails:**
Make sure PostgreSQL is running and your DATABASE_URL is correct.Performance/scaling notes: If your project has specific resource requirements or scaling considerations.
4. Architecture Documentation
Purpose: Explain high-level design decisions and how components interact.
When you need this:
- Projects with multiple services/components
- Complex data flows
- Non-obvious architectural decisions
What to include:
Architecture diagram:
## Architecture┌─────────────┐ ┌──────────────┐ ┌──────────┐ │ Frontend │─────>│ API Server │─────>│ Database │ │ (React) │ │ (Node.js) │ │ (Postgres)│ └─────────────┘ └──────────────┘ └──────────┘ │ ▼ ┌──────────────┐ │ Redis Cache │ └──────────────┘
Use ASCII art, Mermaid diagrams, or tools like draw.io.
Decision records:
## Architecture Decisions
### Why We Chose PostgreSQL Over MongoDB
**Decision:** Use PostgreSQL for primary database
**Reasoning:**
- Need strong consistency for financial transactions
- Relational data model fits our domain well
- Team has more PostgreSQL experience
- Better tooling for migrations
**Trade-offs:**
- Less flexible schema than MongoDB
- More complex queries for deeply nested data
**Alternatives considered:** MongoDB, MySQLData flow examples:
## User Authentication Flow
1. User submits credentials to `/api/login`
2. Server validates against database
3. If valid, generates JWT token
4. Token stored in httpOnly cookie
5. Frontend includes token in subsequent requests
6. Middleware validates token on protected routesComponent responsibilities:
## Component Overview
**Frontend (React):**
- User interface and interaction
- Client-side validation
- State management via Context API
**API Server (Express):**
- Business logic
- Authentication/authorization
- Database queries
- External API integration
**Database (PostgreSQL):**
- Data persistence
- Referential integrity
- Full-text search5. API Documentation
Purpose: Help developers use your API correctly.
For REST APIs:
## API Endpoints
### Authentication
#### POST /api/auth/login
Login with credentials.
**Request:**
```json
{
"email": "user@example.com",
"password": "password123"
}Response (200):
{
"token": "eyJhbGc...",
"user": {
"id": 123,
"email": "user@example.com",
"name": "John Doe"
}
}Errors:
401- Invalid credentials429- Too many attempts, try again in 5 minutes
GET /api/users/:id
Get user by ID.
Parameters:
id(path) - User ID
Response (200):
{
"id": 123,
"email": "user@example.com",
"name": "John Doe",
"createdAt": "2024-01-15T10:30:00Z"
}Errors:
404- User not found403- Unauthorized to view this user
**For GraphQL APIs:**
Link to your GraphQL playground/schema or provide example queries.
**Consider using:**
- Swagger/OpenAPI for auto-generated docs
- Postman collections you can share
- GraphQL schema documentation tools
### 6. Process Documentation
**Purpose:** Document workflows, deployment processes, and operational procedures.
**Examples:**
**Deployment process:**
```markdown
## Deployment
### Production Deployment
1. Ensure all tests pass: `npm test`
2. Update version in package.json
3. Create a release tag: `git tag v1.2.3`
4. Push tags: `git push --tags`
5. GitHub Actions will automatically deploy to production
6. Monitor logs for errors: `heroku logs --tail`
### Rollback Procedure
If deployment fails:
1. Revert to previous version: `heroku rollback`
2. Check logs for errors
3. Fix issues in a new branch
4. Redeploy when readySetting up development environment:
## Development Setup
### Database Setup
1. Install PostgreSQL 14+
2. Create database: `createdb projectname_dev`
3. Run migrations: `npm run migrate`
4. Seed test data: `npm run seed`
### Environment Variables
Copy `.env.example` to `.env` and fill in:DATABASE_URL=postgresql://localhost/projectname_dev JWT_SECRET=generate-a-random-string-here STRIPE_API_KEY=get-from-stripe-dashboard
### Running Locally
Start the development server:
```bash
npm run devHot reload is enabled - changes will auto-refresh.
---
## Documentation Best Practices
### 1. Keep It Updated
**Outdated documentation is worse than no documentation** because it misleads people.
When you change code, update docs in the same PR. If you notice outdated docs, fix them.
### 2. Write for Your Audience
**For end users:** Focus on what they can do and how
**For developers:** Include technical details, architecture, and "why" decisions
### 3. Show, Don't Just Tell
Examples are worth a thousand words:
**Bad:**
```markdown
The API accepts JSON and returns user data.Good:
Send a POST request with JSON:
```bash
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}'Returns:
{
"id": 123,
"name": "John",
"email": "john@example.com"
}
### 4. Use Visuals When Helpful
- Diagrams for architecture or data flow
- Screenshots for UI features
- GIFs for demonstrating interactions
- Code syntax highlighting
### 5. Link Between Documents
Create a web of documentation:
```markdown
See our [API Documentation](api.md) for endpoint details.
Review the [Contributing Guide](CONTRIBUTING.md) before submitting PRs.
Check [Architecture Decisions](docs/architecture.md) for design rationale.6. Include a Table of Contents
For longer documents, add navigation:
## Table of Contents
- [Installation](#installation)
- [Configuration](#configuration)
- [API Reference](#api-reference)
- [Troubleshooting](#troubleshooting)7. Test Your Documentation
Before publishing:
- Follow your own setup instructions on a fresh machine/environment
- Have someone unfamiliar with the project try to use your docs
- Check that all links work
- Verify code examples run correctly
8. Embrace Imperfection
Some documentation is better than perfect documentation that never gets written.
Start with a basic README. Add more as questions come up. Documentation grows with the project.
Documentation Tools
For Code Documentation
- JavaScript/TypeScript: JSDoc → generates HTML docs
- Python: Sphinx + autodoc → generates from docstrings
- Rust:
cargo doc→ built-in documentation - Java: JavaDoc → standard documentation tool
For Project Documentation
- Simple projects: Just README.md and inline comments
- Medium projects: README + docs/ folder with markdown files
- Large projects: Consider these tools:
- MkDocs - Simple, markdown-based
- Docusaurus - React-based, great for versioning
- GitBook - Nice UI, easy to use
- GitHub Wiki - Built-in, low friction
For Diagrams
- Mermaid - Text-based diagrams in markdown
- draw.io - Visual diagram editor
- Excalidraw - Hand-drawn style diagrams
- PlantUML - Code-to-diagram tool
Documentation Checklist
Before considering a project “documented,” check:
- README exists and covers installation, usage, and contribution
- Complex functions have clear docstrings/comments
- Non-obvious code has explanatory comments
- API endpoints are documented with examples
- Architecture decisions are explained
- Setup instructions work on a fresh environment
- All links in docs are valid
- Code examples are tested and work
- Contributing guidelines exist
- License is specified
When Documentation Lives Elsewhere
Sometimes docs need their own repo or site:
Separate docs repo:
- For very large documentation sets
- When docs need different versioning than code
- When non-coders contribute significantly to docs
External sites:
- Product docs on a website (for public-facing projects)
- Internal wiki for process docs
- Team knowledge base (Notion, Confluence, etc.)
If docs live elsewhere, link to them prominently in the README.
Common Documentation Mistakes
Don’t:
- ❌ Write documentation that duplicates what the code says
- ❌ Use jargon without explanation
- ❌ Assume readers know your project’s context
- ❌ Make docs one giant wall of text
- ❌ Leave broken links or outdated examples
- ❌ Use “simply,” “just,” or “obviously” (it’s rarely that simple)
Do:
- ✅ Explain “why” not just “how”
- ✅ Include realistic examples
- ✅ Break docs into digestible sections
- ✅ Update docs when code changes
- ✅ Get feedback from actual users
- ✅ Acknowledge complexity when it exists
Getting Better at Documentation
Documentation is a skill that improves with practice:
- Read good documentation - Notice what makes it helpful
- Read bad documentation - Notice what’s frustrating
- Ask others to test your docs - Fresh eyes catch gaps
- Iterate based on questions - If people keep asking the same thing, document it
- Don’t wait for perfection - Publish and improve over time
Remember: The best documentation is the documentation that exists. Start somewhere, make it better as you go.
Contributing to These Standards
Found something unclear? Have a better approach? These standards evolve based on what works for our projects.
Open an issue, submit a PR, or bring it up at a meeting. Good documentation about documentation helps everyone.