
Codebase Documenter
- 8 installs
- 33 repo stars
- Updated April 26, 2026
- bighardperson/computer-science-skills-collection
This is a copy of codebase-documenter by ailabs-393 - installs and ranking accrue to the original listing.
codebase-documenter is a skill that writes beginner-friendly documentation for a codebase, including READMEs, architecture guides, code comments and API docs.
About
codebase-documenter is a skill for writing documentation for codebases, including README files, architecture docs, code comments and API documentation. It supplies templates and structured approaches aimed at beginner-friendly, accessible docs. A developer uses it when creating getting-started guides or explaining project structure to new contributors.
- Templates and best practices for READMEs, architecture docs, code comments and API docs
- Focuses on beginner-friendly, progressive-disclosure documentation
- Seven core principles including 'Start with the Why' and 'Assume No Prior Knowledge'
Codebase Documenter by the numbers
- 8 all-time installs (skills.sh)
- Data as of Jul 30, 2026 (Skillselion catalog sync)
codebase-documenter capabilities & compatibility
- Capabilities
- api documentation · readme generation · architecture docs
- Use cases
- documentation
What codebase-documenter says it does
This skill should be used when writing documentation for codebases, including README files, architecture documentation, code comments, and API documentation.
This skill enables creating comprehensive, beginner-friendly documentation for codebases.
npx skills add https://github.com/bighardperson/computer-science-skills-collection --skill codebase-documenterAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 8 |
|---|---|
| repo stars | ★ 33 |
| Last updated | April 26, 2026 |
| Repository | bighardperson/computer-science-skills-collection ↗ |
What it does
Write beginner-friendly README, architecture and API documentation for an existing codebase.
Who is it for?
creating clear, beginner-friendly documentation for a codebase
When should I use this skill?
a developer requests help documenting code, creating getting-started guides, or explaining project structure
What you get
Clear README, architecture and API documentation that helps new developers understand and contribute to a project.
- README file
- architecture documentation
- API documentation
By the numbers
- 5 core documentation principles listed
Files
Codebase Documenter
Overview
This skill enables creating comprehensive, beginner-friendly documentation for codebases. It provides structured templates and best practices for writing READMEs, architecture guides, code comments, and API documentation that help new users quickly understand and contribute to projects.
Core Principles for Beginner-Friendly Documentation
When documenting code for new users, follow these fundamental principles:
1. Start with the "Why" - Explain the purpose before diving into implementation details 2. Use Progressive Disclosure - Present information in layers from simple to complex 3. Provide Context - Explain not just what the code does, but why it exists 4. Include Examples - Show concrete usage examples for every concept 5. Assume No Prior Knowledge - Define terms and avoid jargon when possible 6. Visual Aids - Use diagrams, flowcharts, and file tree structures 7. Quick Wins - Help users get something running within 5 minutes
Documentation Types and When to Use Them
1. README Documentation
When to create: For project root directories, major feature modules, or standalone components.
Structure to follow:
# Project Name
## What This Does
[1-2 sentence plain-English explanation]
## Quick Start
[Get users running the project in < 5 minutes]
## Project Structure
[Visual file tree with explanations]
## Key Concepts
[Core concepts users need to understand]
## Common Tasks
[Step-by-step guides for frequent operations]
## Troubleshooting
[Common issues and solutions]Best practices:
- Lead with the project's value proposition
- Include setup instructions that actually work (test them!)
- Provide a visual overview of the project structure
- Link to deeper documentation for advanced topics
- Keep the root README focused on getting started
2. Architecture Documentation
When to create: For projects with multiple modules, complex data flows, or non-obvious design decisions.
Structure to follow:
# Architecture Overview
## System Design
[High-level diagram and explanation]
## Directory Structure
[Detailed breakdown with purpose of each directory]
## Data Flow
[How data moves through the system]
## Key Design Decisions
[Why certain architectural choices were made]
## Module Dependencies
[How different parts interact]
## Extension Points
[Where and how to add new features]Best practices:
- Use diagrams to show system components and relationships
- Explain the "why" behind architectural decisions
- Document both the happy path and error handling
- Identify boundaries between modules
- Include visual file tree structures with annotations
3. Code Comments
When to create: For complex logic, non-obvious algorithms, or code that requires context.
Annotation patterns:
Function/Method Documentation:
/**
* Calculates the prorated subscription cost for a partial billing period.
*
* Why this exists: Users can subscribe mid-month, so we need to charge
* them only for the days remaining in the current billing cycle.
*
* @param {number} fullPrice - The normal monthly subscription price
* @param {Date} startDate - When the user's subscription begins
* @param {Date} periodEnd - End of the current billing period
* @returns {number} The prorated amount to charge
*
* @example
* // User subscribes on Jan 15, period ends Jan 31
* calculateProratedCost(30, new Date('2024-01-15'), new Date('2024-01-31'))
* // Returns: 16.13 (17 days out of 31 days)
*/Complex Logic Documentation:
# Why this check exists: The API returns null for deleted users,
# but empty string for users who never set a name. We need to
# distinguish between these cases for the audit log.
if user_name is None:
# User was deleted - log this as a security event
log_deletion_event(user_id)
elif user_name == "":
# User never completed onboarding - safe to skip
continueBest practices:
- Explain "why" not "what" - the code shows what it does
- Document edge cases and business logic
- Add examples for complex functions
- Explain parameters that aren't self-explanatory
- Note any gotchas or counterintuitive behavior
4. API Documentation
When to create: For any HTTP endpoints, SDK methods, or public interfaces.
Structure to follow:
## Endpoint Name
### What It Does
[Plain-English explanation of the endpoint's purpose]
### Endpoint
`POST /api/v1/resource`
### Authentication
[What auth is required and how to provide it]
### Request Format
[JSON schema or example request]
### Response Format
[JSON schema or example response]
### Example Usage
[Concrete example with curl/code]
### Common Errors
[Error codes and what they mean]
### Related Endpoints
[Links to related operations]Best practices:
- Provide working curl examples
- Show both success and error responses
- Explain authentication clearly
- Document rate limits and constraints
- Include troubleshooting for common issues
Documentation Workflow
Step 1: Analyze the Codebase
Before writing documentation:
1. Identify entry points - Main files, index files, app initialization 2. Map dependencies - How modules relate to each other 3. Find core concepts - Key abstractions users need to understand 4. Locate configuration - Environment setup, config files 5. Review existing docs - Build on what's there, don't duplicate
Step 2: Choose Documentation Type
Based on user request and codebase analysis:
- New project or missing README → Start with README documentation
- Complex architecture or multiple modules → Create architecture documentation
- Confusing code sections → Add inline code comments
- HTTP/API endpoints → Write API documentation
- Multiple types needed → Address in order: README → Architecture → API → Comments
Step 3: Generate Documentation
Use the templates from assets/templates/ as starting points:
assets/templates/README.template.md- For project READMEsassets/templates/ARCHITECTURE.template.md- For architecture docsassets/templates/API.template.md- For API documentation
Customize templates based on the specific codebase:
1. Fill in project-specific information - Replace placeholders with actual content 2. Add concrete examples - Use real code from the project 3. Include visual aids - Create file trees, diagrams, flowcharts 4. Test instructions - Verify setup steps actually work 5. Link related docs - Connect documentation pieces together
Step 4: Review for Clarity
Before finalizing documentation:
1. Read as a beginner - Does it make sense without project context? 2. Check completeness - Are there gaps in the explanation? 3. Verify examples - Do code examples actually work? 4. Test instructions - Can someone follow the setup steps? 5. Improve structure - Is information easy to find?
Documentation Templates
This skill includes several templates in assets/templates/ that provide starting structures:
Available Templates
- README.template.md - Comprehensive README structure with sections for quick start, project structure, and common tasks
- ARCHITECTURE.template.md - Architecture documentation template with system design, data flow, and design decisions
- API.template.md - API endpoint documentation with request/response formats and examples
- CODE_COMMENTS.template.md - Examples and patterns for effective inline documentation
Using Templates
1. Read the appropriate template from assets/templates/ 2. Customize for the specific project - Replace placeholders with actual information 3. Add project-specific sections - Extend the template as needed 4. Include real examples - Use actual code from the codebase 5. Remove irrelevant sections - Delete parts that don't apply
Best Practices Reference
For detailed documentation best practices, style guidelines, and advanced patterns, refer to:
references/documentation_guidelines.md- Comprehensive style guide and best practicesreferences/visual_aids_guide.md- How to create effective diagrams and file trees
Load these references when:
- Creating documentation for complex enterprise codebases
- Dealing with multiple stakeholder requirements
- Needing advanced documentation patterns
- Standardizing documentation across a large project
Common Patterns
Creating File Tree Structures
File trees help new users understand project organization:
project-root/
├── src/ # Source code
│ ├── components/ # Reusable UI components
│ ├── pages/ # Page-level components (routing)
│ ├── services/ # Business logic and API calls
│ ├── utils/ # Helper functions
│ └── types/ # TypeScript type definitions
├── public/ # Static assets (images, fonts)
├── tests/ # Test files mirroring src structure
└── package.json # Dependencies and scriptsExplaining Complex Data Flows
Use numbered steps with diagrams:
User Request Flow:
1. User submits form → 2. Validation → 3. API call → 4. Database → 5. Response
[1] components/UserForm.tsx
↓ validates input
[2] services/validation.ts
↓ sends to API
[3] services/api.ts
↓ queries database
[4] Database (PostgreSQL)
↓ returns data
[5] components/UserForm.tsx (updates UI)Documenting Design Decisions
Capture the "why" behind architectural choices:
## Why We Use Redux
**Decision:** State management with Redux instead of Context API
**Context:** Our app has 50+ components that need access to user
authentication state, shopping cart, and UI preferences.
**Reasoning:**
- Context API causes unnecessary re-renders with this many components
- Redux DevTools helps debug complex state changes
- Team has existing Redux expertise
**Trade-offs:**
- More boilerplate code
- Steeper learning curve for new developers
- Worth it for: performance, debugging, team familiarityOutput Guidelines
When generating documentation:
1. Write for the target audience - Adjust complexity based on whether documentation is for beginners, intermediate, or advanced users 2. Use consistent formatting - Follow markdown conventions, consistent heading hierarchy 3. Provide working examples - Test all code snippets and commands 4. Link between documents - Create a documentation navigation structure 5. Keep it maintainable - Documentation should be easy to update as code changes 6. Add dates and versions - Note when documentation was last updated
Quick Reference
Command to generate README: "Create a README file for this project that helps new developers get started"
Command to document architecture: "Document the architecture of this codebase, explaining how the different modules interact"
Command to add code comments: "Add explanatory comments to this file that help new developers understand the logic"
Command to document API: "Create API documentation for all the endpoints in this file"
{
"ownerId": "kn7agf701n3afzzbq8ge0wa8k1809wm4",
"slug": "codebase-documenter",
"version": "0.1.0",
"publishedAt": 1769869622469
}{
"slug": "codebase-documenter",
"name": "Codebase Documenter",
"version": "0.1.0",
"installedAt": 1776152376525,
"source": "skillhub"
}API Documentation
Overview
This document provides comprehensive documentation for all API endpoints in [Project Name].
Base URL: https://api.example.com/v1
API Version: v1
Last Updated: [Date]
Table of Contents
Authentication
Authentication Method
This API uses [JWT/API Keys/OAuth/etc.] for authentication.
How to authenticate:
1. [Step 1 to get credentials] 2. [Step 2 to use credentials]
Example authentication header:
Authorization: Bearer YOUR_API_TOKEN_HEREGetting your API token:
# Example command or process to obtain token
curl -X POST https://api.example.com/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "user@example.com", "password": "password123"}'Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresAt": "2024-12-31T23:59:59Z"
}Error Handling
Error Response Format
All errors follow this format:
{
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": {
"field": "Additional context about the error"
}
}
}Common Error Codes
| Status Code | Error Code | Description | Solution |
|---|---|---|---|
| 400 | INVALID_REQUEST | Request validation failed | Check request format and required fields |
| 401 | UNAUTHORIZED | Authentication required or failed | Provide valid authentication token |
| 403 | FORBIDDEN | Insufficient permissions | Check user permissions and role |
| 404 | NOT_FOUND | Resource doesn't exist | Verify resource ID and URL |
| 429 | RATE_LIMIT_EXCEEDED | Too many requests | Wait before retrying (check Retry-After header) |
| 500 | INTERNAL_ERROR | Server error | Contact support if persistent |
Error Examples
401 Unauthorized:
{
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid or expired authentication token"
}
}400 Invalid Request:
{
"error": {
"code": "INVALID_REQUEST",
"message": "Validation failed",
"details": {
"email": "Invalid email format",
"age": "Must be a positive number"
}
}
}Rate Limiting
Rate limits:
- Authenticated requests: 1000 requests per hour
- Unauthenticated requests: 100 requests per hour
Rate limit headers:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200When rate limited:
- Status code:
429 Too Many Requests - Response includes
Retry-Afterheader (seconds until reset)
Endpoints
---
[Resource 1 - e.g., Users]
List [Resources]
Retrieve a paginated list of [resources].
Endpoint:
GET /api/v1/[resources]Authentication: Required
Query Parameters:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
page | integer | No | 1 | Page number for pagination |
limit | integer | No | 20 | Number of items per page (max 100) |
sort | string | No | created_at | Sort field (e.g., name, created_at) |
order | string | No | desc | Sort order (asc or desc) |
filter | string | No | - | Filter by [field] |
Example Request:
curl -X GET "https://api.example.com/v1/users?page=1&limit=10&sort=created_at&order=desc" \
-H "Authorization: Bearer YOUR_API_TOKEN"Example Response:
{
"data": [
{
"id": "usr_123abc",
"name": "John Doe",
"email": "john@example.com",
"role": "admin",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
},
{
"id": "usr_456def",
"name": "Jane Smith",
"email": "jane@example.com",
"role": "user",
"created_at": "2024-01-14T15:20:00Z",
"updated_at": "2024-01-14T15:20:00Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 42,
"pages": 5
}
}Response Fields:
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier |
name | string | [Resource] name |
email | string | Email address |
role | string | User role (admin, user, viewer) |
created_at | string (ISO 8601) | Creation timestamp |
updated_at | string (ISO 8601) | Last update timestamp |
---
Get [Resource]
Retrieve a single [resource] by ID.
Endpoint:
GET /api/v1/[resources]/{id}Authentication: Required
Path Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | [Resource] unique identifier |
Example Request:
curl -X GET "https://api.example.com/v1/users/usr_123abc" \
-H "Authorization: Bearer YOUR_API_TOKEN"Example Response:
{
"id": "usr_123abc",
"name": "John Doe",
"email": "john@example.com",
"role": "admin",
"profile": {
"bio": "Software developer",
"location": "San Francisco, CA"
},
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}Possible Errors:
404 NOT_FOUND- [Resource] with specified ID doesn't exist401 UNAUTHORIZED- Invalid or missing authentication token403 FORBIDDEN- Insufficient permissions to view this [resource]
---
Create [Resource]
Create a new [resource].
Endpoint:
POST /api/v1/[resources]Authentication: Required
Request Body:
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | [Resource] name (3-100 characters) |
email | string | Yes | Valid email address |
role | string | No | User role (default: user) |
profile | object | No | Additional profile information |
Example Request:
curl -X POST "https://api.example.com/v1/users" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Alice Johnson",
"email": "alice@example.com",
"role": "user",
"profile": {
"bio": "Product designer",
"location": "New York, NY"
}
}'Example Response:
{
"id": "usr_789ghi",
"name": "Alice Johnson",
"email": "alice@example.com",
"role": "user",
"profile": {
"bio": "Product designer",
"location": "New York, NY"
},
"created_at": "2024-01-16T14:20:00Z",
"updated_at": "2024-01-16T14:20:00Z"
}Possible Errors:
400 INVALID_REQUEST- Validation failed (see error details)401 UNAUTHORIZED- Invalid or missing authentication token403 FORBIDDEN- Insufficient permissions to create [resource]409 CONFLICT- [Resource] with this email already exists
---
Update [Resource]
Update an existing [resource].
Endpoint:
PATCH /api/v1/[resources]/{id}Authentication: Required
Path Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | [Resource] unique identifier |
Request Body:
| Field | Type | Required | Description |
|---|---|---|---|
name | string | No | [Resource] name (3-100 characters) |
email | string | No | Valid email address |
role | string | No | User role |
profile | object | No | Additional profile information |
Note: Only include fields you want to update. Omitted fields remain unchanged.
Example Request:
curl -X PATCH "https://api.example.com/v1/users/usr_123abc" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"role": "admin",
"profile": {
"bio": "Senior Software Developer"
}
}'Example Response:
{
"id": "usr_123abc",
"name": "John Doe",
"email": "john@example.com",
"role": "admin",
"profile": {
"bio": "Senior Software Developer",
"location": "San Francisco, CA"
},
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-16T15:00:00Z"
}Possible Errors:
400 INVALID_REQUEST- Validation failed401 UNAUTHORIZED- Invalid or missing authentication token403 FORBIDDEN- Insufficient permissions to update this [resource]404 NOT_FOUND- [Resource] with specified ID doesn't exist
---
Delete [Resource]
Delete a [resource].
Endpoint:
DELETE /api/v1/[resources]/{id}Authentication: Required
Path Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | [Resource] unique identifier |
Example Request:
curl -X DELETE "https://api.example.com/v1/users/usr_123abc" \
-H "Authorization: Bearer YOUR_API_TOKEN"Example Response:
{
"success": true,
"message": "[Resource] deleted successfully"
}Possible Errors:
401 UNAUTHORIZED- Invalid or missing authentication token403 FORBIDDEN- Insufficient permissions to delete this [resource]404 NOT_FOUND- [Resource] with specified ID doesn't exist
---
[Resource 2 - e.g., Projects]
[Repeat the same pattern for another resource: List, Get, Create, Update, Delete]
---
Webhooks
Overview
[If your API supports webhooks, document them here]
Webhook endpoint requirements:
- Must accept POST requests
- Must respond with 200 status within 5 seconds
- Must use HTTPS
Available Events
| Event | Description | Triggered When |
|---|---|---|
[resource].created | [Resource] was created | New [resource] is created |
[resource].updated | [Resource] was updated | [Resource] is modified |
[resource].deleted | [Resource] was deleted | [Resource] is deleted |
Webhook Payload
{
"event": "[resource].created",
"timestamp": "2024-01-16T15:30:00Z",
"data": {
"id": "usr_123abc",
"name": "John Doe",
"email": "john@example.com"
}
}Verifying Webhooks
[Explain how to verify webhook authenticity, e.g., signature verification]
---
SDK Examples
JavaScript/TypeScript
// Install: npm install @example/api-client
import { APIClient } from '@example/api-client';
const client = new APIClient({
apiKey: 'YOUR_API_TOKEN'
});
// List resources
const users = await client.users.list({
page: 1,
limit: 10
});
// Get single resource
const user = await client.users.get('usr_123abc');
// Create resource
const newUser = await client.users.create({
name: 'Alice Johnson',
email: 'alice@example.com'
});
// Update resource
const updatedUser = await client.users.update('usr_123abc', {
role: 'admin'
});
// Delete resource
await client.users.delete('usr_123abc');Python
# Install: pip install example-api-client
from example_api import APIClient
client = APIClient(api_key='YOUR_API_TOKEN')
# List resources
users = client.users.list(page=1, limit=10)
# Get single resource
user = client.users.get('usr_123abc')
# Create resource
new_user = client.users.create(
name='Alice Johnson',
email='alice@example.com'
)
# Update resource
updated_user = client.users.update(
'usr_123abc',
role='admin'
)
# Delete resource
client.users.delete('usr_123abc')---
Best Practices
Pagination
Always paginate list endpoints to avoid performance issues:
- Use
limitparameter to control page size - Don't request more than 100 items per page
- Use
pageparameter for subsequent pages
Error Handling
Implement proper error handling:
try {
const user = await client.users.get('usr_123abc');
} catch (error) {
if (error.code === 'NOT_FOUND') {
console.log('User not found');
} else if (error.code === 'UNAUTHORIZED') {
console.log('Authentication failed');
} else {
console.log('Unexpected error:', error.message);
}
}Rate Limiting
Monitor rate limit headers and implement backoff:
const response = await fetch(url, options);
const remaining = response.headers.get('X-RateLimit-Remaining');
if (remaining < 10) {
console.warn('Approaching rate limit');
}---
Support
Questions or issues?
- Documentation: [link]
- Support email: [email]
- Community forum: [link]
- Issue tracker: [link]
API Status:
- Status page: [link]
- Uptime: [link]
Architecture Overview
What This Document Covers
This document explains the high-level architecture of [Project Name], including how different components interact, key design decisions, and where to make common changes.
Target audience: Developers who need to understand the system design before making significant changes.
System Design
High-Level Architecture
[Create a simple ASCII diagram or describe components]
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Frontend │─────▶│ Backend │─────▶│ Database │
│ (React) │◀─────│ (Node.js) │◀─────│ (Postgres) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │
│ ▼
│ ┌─────────────┐
└────────────▶│ API Layer │
└─────────────┘Components:
1. Frontend - [Explain what this component does and its responsibilities] 2. Backend - [Explain what this component does and its responsibilities] 3. Database - [Explain what data is stored and how it's organized] 4. API Layer - [Explain how components communicate]
Technology Stack
| Layer | Technology | Why We Chose It |
|---|---|---|
| Frontend | [Technology] | [Reasoning for choice] |
| Backend | [Technology] | [Reasoning for choice] |
| Database | [Technology] | [Reasoning for choice] |
| Hosting | [Technology] | [Reasoning for choice] |
Directory Structure
project-root/
├── src/
│ ├── components/ # Reusable UI components
│ │ ├── common/ # Shared components (buttons, inputs, etc.)
│ │ ├── features/ # Feature-specific components
│ │ └── layout/ # Layout components (header, footer, etc.)
│ │
│ ├── pages/ # Page-level components (one per route)
│ │ ├── Home/ # Home page and related components
│ │ ├── Dashboard/ # Dashboard page and related components
│ │ └── Settings/ # Settings page and related components
│ │
│ ├── services/ # Business logic and external integrations
│ │ ├── api.js # API client configuration
│ │ ├── auth.js # Authentication logic
│ │ └── [feature].js # Feature-specific business logic
│ │
│ ├── store/ # State management (Redux/Context/etc.)
│ │ ├── slices/ # State slices by feature
│ │ └── store.js # Store configuration
│ │
│ ├── utils/ # Helper functions and utilities
│ │ ├── validation.js # Input validation helpers
│ │ ├── formatting.js # Data formatting utilities
│ │ └── constants.js # App-wide constants
│ │
│ ├── hooks/ # Custom React hooks
│ │ └── use[Feature].js # Feature-specific hooks
│ │
│ ├── types/ # TypeScript type definitions
│ │ ├── models.ts # Data model types
│ │ └── api.ts # API request/response types
│ │
│ └── index.js # Application entry point
│
├── tests/ # Test files (mirrors src/ structure)
├── public/ # Static assets
├── config/ # Configuration files
└── [build-output]/ # Build artifacts (gitignored)Directory Purpose and Rules
components/
Purpose: Reusable UI components that don't contain business logic.
What goes here:
- Presentational components (buttons, cards, modals)
- Layout components (headers, sidebars, containers)
- Feature-specific components used in multiple places
What doesn't go here:
- Business logic (put in
services/) - Page-level components (put in
pages/) - One-off components used in a single place (colocate with parent)
When to add a file: When you need a reusable component used in 2+ places.
services/
Purpose: Business logic, API calls, and external service integrations.
What goes here:
- API client functions
- Authentication and authorization logic
- Data transformation and validation
- Third-party service integrations
What doesn't go here:
- UI components (put in
components/) - State management (put in
store/) - Pure utility functions (put in
utils/)
When to add a file: When you need to interact with external services or implement complex business logic.
utils/
Purpose: Pure utility functions with no side effects.
What goes here:
- Data formatting and parsing
- Validation helpers
- Constants and enumerations
- Date/time utilities
What doesn't go here:
- Functions that make API calls (put in
services/) - Functions that depend on React (make a custom hook in
hooks/) - Functions specific to one component (colocate with component)
When to add a file: When you have a pure function used in 3+ places.
Data Flow
[Feature Name] Flow
Explain how data flows through the system for a key feature:
User Action → Component → Service → API → Database
↓
State Update
↓
UI Re-renderStep-by-step:
1. User triggers action in components/FeatureComponent.tsx
- User clicks button, submits form, etc.
- Component calls
handleAction()function
2. Component dispatches action to state management
- Calls
dispatch(featureAction(data)) - State is updated optimistically
3. Service layer processes request in services/feature.js
- Validates input data
- Transforms data to API format
- Makes HTTP request to backend
4. Backend processes request in api/feature/route.js
- Validates authentication
- Applies business logic
- Updates database
5. Response flows back through the layers
- Backend returns success/error
- Service layer transforms response
- State is updated with final result
- Component re-renders with new data
State Management
Architecture: [Describe state management approach - Redux, Context API, Zustand, etc.]
State organization:
Global State
├── auth # User authentication state
├── user # User profile data
├── [feature1] # Feature-specific state
├── [feature2] # Feature-specific state
└── ui # UI state (modals, loading, etc.)Data flow rules:
- Components read state via [hooks/selectors]
- Components update state via [dispatch/setState functions]
- Async operations handled in [middleware/thunks/services]
Key Design Decisions
Decision 1: [Architecture Choice]
What we decided: [Describe the decision made]
Context: [Explain the situation that required this decision]
- [Constraint or requirement 1]
- [Constraint or requirement 2]
Why we decided this:
- Reason 1: [Explain benefit]
- Reason 2: [Explain benefit]
- Reason 3: [Explain benefit]
Trade-offs:
- ✅ Pros: [What we gained]
- ❌ Cons: [What we sacrificed]
- 🤔 When to reconsider: [Conditions that might make this decision obsolete]
Alternatives considered:
- [Alternative 1]: Rejected because [reason]
- [Alternative 2]: Rejected because [reason]
Decision 2: [Technology Choice]
What we decided: [Describe the decision made]
Context: [Explain the situation that required this decision]
Why we decided this:
- [Reason 1]
- [Reason 2]
Trade-offs:
- ✅ Pros: [What we gained]
- ❌ Cons: [What we sacrificed]
Alternatives considered:
- [Alternative 1]: Rejected because [reason]
- [Alternative 2]: Rejected because [reason]
Module Dependencies
Dependency Graph
pages/
└─→ components/
└─→ hooks/
└─→ services/
└─→ utils/
store/
└─→ services/
└─→ utils/Dependency rules: 1. Lower layers can't depend on higher layers
- ❌
services/can't import fromcomponents/ - ✅
components/can import fromservices/
2. Same-level imports require careful consideration
- 🤔 Components importing other components: Usually OK
- ⚠️ Services importing other services: Consider refactoring
3. Avoid circular dependencies
- Use dependency injection or event systems when needed
External Dependencies
| Package | Version | Used For | Notes |
|---|---|---|---|
| [package-name] | [version] | [purpose] | [Important notes or alternatives] |
| [package-name] | [version] | [purpose] | [Important notes or alternatives] |
Extension Points
Adding a New Feature
To add a new feature to the codebase:
1. Create feature structure:
src/
├── components/features/[FeatureName]/
├── services/[featureName].js
└── store/slices/[featureName]Slice.js2. Implement components:
- Create UI components in
components/features/[FeatureName]/ - Follow existing component patterns
- Use shared components from
components/common/
3. Add business logic:
- Create service file in
services/[featureName].js - Implement API calls and data transformations
- Follow existing error handling patterns
4. Set up state management:
- Create slice in
store/slices/[featureName]Slice.js - Define actions and reducers
- Export selectors for components
5. Add routes (if applicable):
- Register new routes in
routes.js - Create page component in
pages/[FeatureName]/
6. Add tests:
- Mirror structure in
tests/ - Test components, services, and state
Common Modification Points
Adding a new API endpoint:
- Backend: Create route in
api/[feature]/route.js - Frontend: Add service function in
services/[feature].js - Update types in
types/api.ts
Adding a new database table:
- Create migration in
migrations/ - Add model in
models/[tableName].js - Update seed data if applicable
Adding a new component library:
- Install package:
npm install [package] - Create wrapper in
components/common/[ComponentName]/ - Configure theme/styling in
config/theme.js
Performance Considerations
Critical Performance Paths
1. [Path 1: e.g., Initial page load]
- Current performance: [metrics]
- Bottlenecks: [known issues]
- Optimization strategy: [approach]
2. [Path 2: e.g., Search functionality]
- Current performance: [metrics]
- Bottlenecks: [known issues]
- Optimization strategy: [approach]
Caching Strategy
What we cache:
- [Data type 1]: Cached in [location] for [duration]
- [Data type 2]: Cached in [location] for [duration]
Cache invalidation:
- [Trigger 1]: Clears [cache type]
- [Trigger 2]: Clears [cache type]
Security Architecture
Authentication Flow
[Describe how users authenticate]
1. User submits credentials 2. Backend validates and issues [JWT/session/etc.] 3. Token stored in [location] 4. Subsequent requests include token
Authorization
Permission levels:
- [Role 1]: Can [actions]
- [Role 2]: Can [actions]
- [Role 3]: Can [actions]
Implementation:
- Frontend: Check permissions in [location]
- Backend: Enforce permissions in [location]
Data Security
- Sensitive data encrypted at rest: [Yes/No - how]
- API communications: [HTTPS/TLS version]
- Input validation: [Where and how]
- XSS protection: [Strategy]
- CSRF protection: [Strategy]
Deployment Architecture
Environments
| Environment | URL | Purpose | Auto-deploys |
|---|---|---|---|
| Development | [url] | Local development | No |
| Staging | [url] | Testing before production | Yes (main branch) |
| Production | [url] | Live application | Yes (release tags) |
Build Process
# Development build
[build-command-dev]
# Production build
[build-command-prod]Build artifacts:
- Output location: [path]
- Artifacts: [list of generated files]
Deployment Steps
1. [Step 1] 2. [Step 2] 3. [Step 3]
Monitoring and Observability
Logging
Log levels:
- ERROR: [What gets logged]
- WARN: [What gets logged]
- INFO: [What gets logged]
Log destinations:
- Development: [Console/file]
- Production: [Service name/location]
Metrics
Key metrics tracked:
- [Metric 1]: [What it measures]
- [Metric 2]: [What it measures]
Monitoring tools:
- [Tool name]: [What we monitor with it]
Troubleshooting
Common Architecture Issues
Issue: [Common problem]
- Symptoms: [How to recognize it]
- Cause: [Why it happens]
- Solution: [How to fix it]
Additional Resources
- [Link to API documentation]
- [Link to database schema]
- [Link to deployment guide]
- [Link to contributing guidelines]
Questions and Feedback
If you have questions about the architecture or suggestions for improvements:
- [Contact method]
- [Issue tracker link]
Code Comments Guide
This document provides examples and patterns for writing effective inline documentation that helps new developers understand code quickly.
Core Principles
1. Explain "Why" not "What" - The code shows what it does; comments should explain why it exists 2. Provide Context - Help readers understand the bigger picture 3. Document Edge Cases - Explain non-obvious behavior and special handling 4. Include Examples - Show how to use complex functions 5. Keep Comments Current - Update comments when code changes
Function/Method Documentation
JavaScript/TypeScript (JSDoc)
/**
* Calculates the prorated subscription cost for a partial billing period.
*
* Why this exists: Users can subscribe mid-month, so we need to charge
* them only for the days remaining in the current billing cycle.
*
* @param {number} fullPrice - The normal monthly subscription price
* @param {Date} startDate - When the user's subscription begins
* @param {Date} periodEnd - End of the current billing period
* @returns {number} The prorated amount to charge
*
* @example
* // User subscribes on Jan 15, period ends Jan 31
* calculateProratedCost(30, new Date('2024-01-15'), new Date('2024-01-31'))
* // Returns: 16.13 (17 days out of 31 days * $30)
*
* @throws {Error} If startDate is after periodEnd
*/
function calculateProratedCost(fullPrice, startDate, periodEnd) {
if (startDate > periodEnd) {
throw new Error('Start date must be before period end');
}
const daysInPeriod = (periodEnd - startDate) / (1000 * 60 * 60 * 24);
const daysInMonth = new Date(periodEnd.getYear(), periodEnd.getMonth() + 1, 0).getDate();
return (fullPrice / daysInMonth) * daysInPeriod;
}Python (Docstring)
def calculate_prorated_cost(full_price: float, start_date: datetime, period_end: datetime) -> float:
"""
Calculates the prorated subscription cost for a partial billing period.
Why this exists: Users can subscribe mid-month, so we need to charge
them only for the days remaining in the current billing cycle.
Args:
full_price: The normal monthly subscription price
start_date: When the user's subscription begins
period_end: End of the current billing period
Returns:
The prorated amount to charge
Raises:
ValueError: If start_date is after period_end
Example:
>>> # User subscribes on Jan 15, period ends Jan 31
>>> calculate_prorated_cost(30, date(2024, 1, 15), date(2024, 1, 31))
16.13 # 17 days out of 31 days * $30
"""
if start_date > period_end:
raise ValueError('Start date must be before period end')
days_in_period = (period_end - start_date).days
days_in_month = monthrange(period_end.year, period_end.month)[1]
return (full_price / days_in_month) * days_in_periodJava (JavaDoc)
/**
* Calculates the prorated subscription cost for a partial billing period.
*
* <p>Why this exists: Users can subscribe mid-month, so we need to charge
* them only for the days remaining in the current billing cycle.</p>
*
* @param fullPrice The normal monthly subscription price
* @param startDate When the user's subscription begins
* @param periodEnd End of the current billing period
* @return The prorated amount to charge
* @throws IllegalArgumentException if startDate is after periodEnd
*
* <p>Example:
* <pre>
* // User subscribes on Jan 15, period ends Jan 31
* double cost = calculateProratedCost(30.0,
* LocalDate.of(2024, 1, 15),
* LocalDate.of(2024, 1, 31));
* // Returns: 16.13 (17 days out of 31 days * $30)
* </pre>
*/
public double calculateProratedCost(double fullPrice, LocalDate startDate, LocalDate periodEnd) {
if (startDate.isAfter(periodEnd)) {
throw new IllegalArgumentException("Start date must be before period end");
}
long daysInPeriod = ChronoUnit.DAYS.between(startDate, periodEnd);
int daysInMonth = periodEnd.lengthOfMonth();
return (fullPrice / daysInMonth) * daysInPeriod;
}Complex Logic Documentation
Documenting Business Rules
// Why we check status in this specific order:
// 1. "cancelled" takes precedence because users might cancel during trial
// 2. "trial" is checked next so we can show trial-specific messaging
// 3. "active" is the default state for paying customers
// This ordering prevents edge cases like showing "active" status to
// cancelled trial users.
if (subscription.status === 'cancelled') {
return <CancelledMessage />;
} else if (subscription.status === 'trial') {
return <TrialMessage daysRemaining={subscription.trialDaysLeft} />;
} else if (subscription.status === 'active') {
return <ActiveMessage />;
}Documenting Edge Cases
# Why this check exists: The API returns None for deleted users,
# but empty string for users who never set a name. We need to
# distinguish between these cases for the audit log.
if user_name is None:
# User was deleted - log this as a security event
log_deletion_event(user_id, timestamp=datetime.now())
elif user_name == "":
# User never completed onboarding - safe to skip
continue
else:
# Normal case - process the user
process_user(user_id, user_name)Documenting Performance Considerations
// Performance note: We use a Set here instead of an Array because
// we frequently check if user IDs exist (O(1) lookup vs O(n)).
// With 10,000+ users, this saves ~500ms per request.
const activeUserIds = new Set(users.map(u => u.id));
// Avoid: const activeUserIds = users.map(u => u.id); // O(n) lookups
if (activeUserIds.has(currentUserId)) {
// User is active
}Documenting Workarounds and Gotchas
# GOTCHA: The third-party API returns timestamps in Unix milliseconds,
# but Python's datetime expects seconds. We must divide by 1000.
# Bug reported upstream: https://github.com/vendor/lib/issues/123
timestamp = datetime.fromtimestamp(api_response['created_at'] / 1000)// WORKAROUND: Safari doesn't support lookbehind regex, so we use
// a more verbose approach here. Can simplify once we drop Safari 15 support.
// TODO: Replace with lookbehind regex when Safari 15+ usage drops below 1%
// Original regex: /(?<=@)\w+/g
const mentions = text.split('@').slice(1).map(part => part.split(/\s/)[0]);Class Documentation
TypeScript Class
/**
* Manages user authentication state and provides methods for login/logout.
*
* Why this exists: We need centralized auth state management that works
* across multiple components and persists across page refreshes.
*
* Usage:
* ```typescript
* const auth = new AuthManager();
*
* // Log in user
* await auth.login('user@example.com', 'password');
*
* // Check if user is authenticated
* if (auth.isAuthenticated()) {
* // Show authenticated content
* }
*
* // Get current user
* const user = auth.getCurrentUser();
* ```
*/
class AuthManager {
private token: string | null = null;
private user: User | null = null;
/**
* Authenticates a user with email and password.
*
* Why async: Makes API call to backend for authentication.
* Side effects: Stores token in localStorage and updates internal state.
*
* @throws {AuthenticationError} If credentials are invalid
*/
async login(email: string, password: string): Promise<User> {
// Implementation
}
/**
* Checks if a user is currently authenticated.
*
* Note: Performs local check only; doesn't verify token with backend.
* Use refreshToken() if you need to verify token is still valid.
*/
isAuthenticated(): boolean {
return this.token !== null && !this.isTokenExpired();
}
/**
* Checks if the current token has expired.
*
* Implementation note: Tokens expire 24 hours after issue.
* We check 5 minutes before actual expiry to avoid edge cases.
*/
private isTokenExpired(): boolean {
// Implementation
}
}Algorithm Documentation
Complex Algorithm
def find_shortest_path(graph, start, end):
"""
Finds the shortest path between two nodes using Dijkstra's algorithm.
Why we chose Dijkstra: We have a weighted graph with non-negative weights.
If we had negative weights, we'd need Bellman-Ford instead.
Time Complexity: O((V + E) log V) where V = vertices, E = edges
Space Complexity: O(V) for storing distances and visited nodes
Algorithm overview:
1. Initialize distances to all nodes as infinity, except start (0)
2. Use priority queue to always process closest unvisited node
3. For each neighbor, check if we found a shorter path
4. Continue until we reach the end node or exhaust all paths
Args:
graph: Adjacency list representation {node: [(neighbor, weight), ...]}
start: Starting node
end: Destination node
Returns:
List of nodes representing shortest path, or None if no path exists
Example:
>>> graph = {
... 'A': [('B', 4), ('C', 2)],
... 'B': [('D', 3)],
... 'C': [('B', 1), ('D', 5)],
... 'D': []
... }
>>> find_shortest_path(graph, 'A', 'D')
['A', 'C', 'B', 'D'] # Cost: 6 (A->C: 2, C->B: 1, B->D: 3)
"""
# Priority queue: [(distance, node, path)]
# We store the full path to reconstruct it at the end
queue = [(0, start, [start])]
visited = set()
while queue:
# Pop node with smallest distance (priority queue property)
distance, node, path = heapq.heappop(queue)
# Skip if we've already processed this node
# Important: Prevents infinite loops in cyclic graphs
if node in visited:
continue
visited.add(node)
# Success case: we reached the destination
if node == end:
return path
# Explore neighbors
for neighbor, weight in graph.get(node, []):
if neighbor not in visited:
# Calculate distance to neighbor through current path
new_distance = distance + weight
new_path = path + [neighbor]
heapq.heappush(queue, (new_distance, neighbor, new_path))
# No path exists between start and end
return NoneAPI Integration Documentation
/**
* Fetches user data from the legacy API with proper error handling.
*
* API Quirks to be aware of:
* 1. Returns 200 with error object instead of proper status codes
* 2. Rate limit is 100 req/min but not documented in headers
* 3. User IDs are strings, not numbers (despite API docs saying otherwise)
* 4. Deleted users return {deleted: true} instead of 404
*
* Related Jira tickets:
* - API-123: Rate limit enhancement request
* - API-456: Proper status codes migration (planned for Q2)
*
* @param {string} userId - User ID as string (e.g., "usr_123abc")
* @returns {Promise<User|null>} User object or null if deleted
* @throws {APIError} If API is unavailable or rate limited
*/
async function fetchUserFromLegacyAPI(userId) {
try {
const response = await fetch(`https://legacy-api.example.com/users/${userId}`);
// Check for pseudo-error responses (API returns 200 with error object)
if (response.ok) {
const data = await response.json();
// Check for API's custom error format
if (data.error) {
throw new APIError(data.error.message, data.error.code);
}
// Check for deleted user (API quirk #4)
if (data.deleted === true) {
return null;
}
return data;
}
throw new APIError(`API returned ${response.status}`, response.status);
} catch (error) {
// Add context to help with debugging
throw new APIError(`Failed to fetch user ${userId}: ${error.message}`);
}
}Configuration Documentation
// Database connection configuration
//
// Pool size tuning: After load testing, we found:
// - 10 connections: good for < 100 concurrent users
// - 20 connections: good for 100-500 concurrent users
// - 50 connections: good for 500-2000 concurrent users
// - Beyond 2000: consider read replicas
//
// Current setting (20) is sized for our typical load of ~300 concurrent users
// Last updated: 2024-01-15 after Q4 traffic analysis
const dbConfig = {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT || '5432'),
database: process.env.DB_NAME,
// Connection pooling
max: 20, // Maximum number of connections in pool
min: 5, // Minimum number of connections (always maintained)
// Timeout settings
// - connectionTimeoutMillis: How long to wait for a connection from pool
// - idleTimeoutMillis: How long a connection can sit idle before being closed
// - query_timeout: PostgreSQL-specific timeout for long-running queries
connectionTimeoutMillis: 5000, // Fail fast if pool is exhausted
idleTimeoutMillis: 30000, // Close idle connections after 30s
query_timeout: 60000, // Kill queries running longer than 60s
};TODO Comments
Use TODO comments effectively:
// TODO(username, 2024-01-15): Implement caching for this endpoint
// Why: API call takes 500ms, users report slowness
// Impact: High - affects all list views
// Complexity: Medium - need to handle cache invalidation
// Ticket: PERF-123
async function getUserList() {
return await api.get('/users');
}
// TODO(username): Refactor to use new auth system
// Blocked by: AUTH-456 (auth system migration)
// Can remove after: All clients migrate to v2 API
function legacyAuthCheck(token) {
// Old auth logic
}
// FIXME(username): This breaks when month has 31 days
// Bug report: BUG-789
// Workaround: Validate date before passing to this function
function calculateEndDate(startDay, daysToAdd) {
return startDay + daysToAdd; // Simplified example
}
// HACK(username): Temporary workaround for Safari bug
// Remove when: Safari 16 usage drops below 5%
// Tracking: https://bugs.webkit.org/show_bug.cgi?id=12345
if (isSafari()) {
// Workaround code
}When NOT to Write Comments
Don't Explain Obvious Code
// ❌ BAD: Comment explains what code obviously does
// Increment counter by 1
counter++;
// ✅ GOOD: No comment needed, code is self-explanatory
counter++;Don't Describe Implementation That's Clear
// ❌ BAD: Describes obvious loop logic
// Loop through all users and find the one with matching ID
const user = users.find(u => u.id === userId);
// ✅ GOOD: No comment needed, code is clear
const user = users.find(u => u.id === userId);Don't Leave Commented-Out Code
// ❌ BAD: Leaving old code as comments
function calculateTotal(items) {
// return items.reduce((sum, item) => sum + item.price, 0);
// return items.map(i => i.price).reduce((a, b) => a + b);
return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
// ✅ GOOD: Delete old code, use version control instead
function calculateTotal(items) {
return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}Summary
Good comments:
- Explain WHY, not WHAT
- Provide context and business logic
- Document edge cases and gotchas
- Include examples for complex functions
- Note performance considerations
- Explain workarounds with links to issues
Avoid:
- Describing obvious code
- Leaving commented-out code
- Outdated information
- Redundant descriptions
- Comments that duplicate code
[Project Name]
What This Does
[Write 1-2 sentences explaining what this project does in plain English. Focus on the value it provides, not the technical implementation.]
Example: "This is a task management application that helps teams track project progress and collaborate on deliverables. It provides real-time updates and integrates with popular project management tools."
Quick Start
Get up and running in under 5 minutes:
Prerequisites
- [List required software/tools with versions]
- Example: Node.js 18+ or Python 3.9+
- Example: PostgreSQL 14+
- Example: API keys from [Service Name]
Installation
# Clone the repository
git clone [repository-url]
cd [project-name]
# Install dependencies
[package-manager] install
# Set up environment variables
cp .env.example .env
# Edit .env with your configuration
# Run database migrations (if applicable)
[migration-command]
# Start the development server
[start-command]Verify It's Working
[Provide a quick way to verify the installation succeeded]
- Example: "Open http://localhost:3000 in your browser"
- Example: "Run
npm testto verify all tests pass" - Example: "You should see [specific output/page]"
Project Structure
project-root/
├── src/ # Source code
│ ├── components/ # [Explain what goes here]
│ ├── services/ # [Explain what goes here]
│ ├── utils/ # [Explain what goes here]
│ └── index.js # [Explain what this file does]
├── tests/ # Test files
├── public/ # Static assets
├── config/ # Configuration files
├── .env.example # Environment variable template
├── package.json # Dependencies and scripts
└── README.md # This fileKey Directories Explained
src/components/ - [Detailed explanation of what goes in this directory and when to add files here]
src/services/ - [Detailed explanation of what goes in this directory and when to add files here]
src/utils/ - [Detailed explanation of what goes in this directory and when to add files here]
Key Concepts
[Concept 1 - Core Abstraction]
[Explain a key concept that users need to understand to work with this codebase]
Why this matters: [Explain why understanding this concept is important]
Example:
// Show a concrete code example demonstrating this concept[Concept 2 - Important Pattern]
[Explain another important concept]
Why this matters: [Explain why understanding this concept is important]
Example:
// Show a concrete code example demonstrating this conceptCommon Tasks
[Task 1: Common Operation]
[Step-by-step guide for a task users will frequently perform]
1. First step with command: command-here 2. Second step with explanation 3. Third step with expected outcome
Expected result: [What should happen when this task succeeds]
[Task 2: Another Common Operation]
[Step-by-step guide for another frequent task]
1. First step with command: command-here 2. Second step with explanation 3. Third step with expected outcome
Expected result: [What should happen when this task succeeds]
[Task 3: Development Workflow]
[Explain the typical development workflow]
1. Create a new branch: git checkout -b feature/your-feature 2. Make your changes 3. Run tests: [test-command] 4. Commit your changes: git commit -m "Description" 5. Push and create pull request
Configuration
Environment Variables
| Variable | Description | Example | Required |
|---|---|---|---|
VAR_NAME | [What this variable controls] | example-value | Yes |
API_KEY | [What this variable controls] | sk_test_123abc | Yes |
DEBUG | [What this variable controls] | true | No |
Configuration Files
config/[file-name].js - [Explain what this config file controls and when to modify it]
Development
Running Tests
# Run all tests
[test-command]
# Run specific test file
[specific-test-command]
# Run with coverage
[coverage-command]Code Style
[Explain code style conventions]
- [Convention 1]
- [Convention 2]
- Run linter:
[lint-command] - Format code:
[format-command]
Debugging
[Provide tips for debugging]
Common debugging commands:
# Command to enable debug mode
DEBUG=* [start-command]
# Command to see detailed logs
[log-command]Troubleshooting
[Common Issue 1]
Problem: [Describe the problem users might encounter]
Solution: [Step-by-step solution]
# Commands to fix the issue[Common Issue 2]
Problem: [Describe the problem users might encounter]
Solution: [Step-by-step solution]
# Commands to fix the issue[Common Issue 3]
Problem: [Describe the problem users might encounter]
Solution: [Step-by-step solution]
Additional Documentation
- ARCHITECTURE.md - Detailed system architecture
- API.md - API endpoint documentation
- CONTRIBUTING.md - Contribution guidelines
- [Link to external docs if applicable]
Getting Help
- Check existing issues: [link to issues]
- Join our community: [link to Discord/Slack/forum]
- Contact: [email or contact method]
License
[License information]
export default async function codebase_documenter(input) {
console.log("🧠 Running skill: codebase-documenter");
// TODO: implement actual logic for this skill
return {
message: "Skill 'codebase-documenter' executed successfully!",
input
};
}
{
"name": "@ai-labs-claude-skills/codebase-documenter",
"version": "1.0.0",
"description": "Claude AI skill: codebase-documenter",
"main": "index.js",
"files": [
"."
],
"license": "MIT",
"author": "AI Labs"
}Documentation Guidelines
This reference provides comprehensive best practices and style guidelines for creating high-quality documentation.
Writing Style Guide
Voice and Tone
Use active voice:
- ✅ "The function returns a user object"
- ❌ "A user object is returned by the function"
Be direct and concise:
- ✅ "Install dependencies with
npm install" - ❌ "You can install the dependencies by running the npm install command"
Use present tense:
- ✅ "The API returns an error when..."
- ❌ "The API will return an error when..."
Avoid unnecessary words:
- ✅ "To start the server, run..."
- ❌ "In order to start the server, you will need to run..."
Technical Writing Conventions
Code formatting:
- Use backticks for inline code:
variable,function(),npm install - Use code blocks for multi-line code with language specification
- Include command prompts (
$,>) only when necessary for clarity
Capitalization:
- Use sentence case for headings: "Getting started" not "Getting Started"
- Capitalize proper nouns: "Docker", "PostgreSQL", "JavaScript"
- Lowercase for commands and file names:
npm,package.json,index.js
Punctuation:
- Use periods for complete sentences
- No periods for list items that aren't complete sentences
- Use serial comma: "red, white, and blue"
Lists:
- Use numbered lists for sequential steps
- Use bullet lists for non-sequential items
- Indent sub-items consistently
Structure Patterns
Progressive Disclosure
Organize information from simple to complex:
## Getting Started
[Basic usage example that works immediately]
## Core Concepts
[Key concepts needed to understand the system]
## Advanced Usage
[Complex scenarios and edge cases]
## API Reference
[Complete technical reference]Task-Oriented Structure
Organize by what users want to accomplish:
## Common Tasks
### Adding a new feature
[Step-by-step instructions]
### Debugging issues
[Troubleshooting guide]
### Deploying to production
[Deployment instructions]The "Five-Minute Rule"
Every project should have a path that gets users to success in under 5 minutes:
1. Quick Start section at the top 2. Minimal setup steps 3. One working example 4. Clear success indicator ("You should see...") 5. Link to deeper docs for next steps
Content Guidelines
Code Examples
Make examples realistic:
- ✅ Use real-world variable names and scenarios
- ❌ Don't use
foo,bar,bazunless explaining general concepts
// ✅ GOOD: Realistic example
const user = await fetchUser('usr_123');
if (user.role === 'admin') {
showAdminPanel();
}
// ❌ BAD: Unclear example
const foo = await bar('baz');
if (foo.x === 'y') {
doThing();
}Include context:
// ✅ GOOD: Shows where this code lives
// src/services/auth.js
export async function login(email, password) {
// Implementation
}
// ❌ BAD: No context about where to put this
async function login(email, password) {
// Implementation
}Show complete examples:
// ✅ GOOD: Complete, runnable example
import { createUser } from './services/user';
async function example() {
try {
const user = await createUser({
name: 'John Doe',
email: 'john@example.com'
});
console.log('User created:', user.id);
} catch (error) {
console.error('Failed to create user:', error);
}
}
// ❌ BAD: Incomplete example
const user = await createUser({...});Error Documentation
Document error messages:
### Common Errors
**Error: `ECONNREFUSED`**
- **Cause:** Database is not running
- **Solution:** Start the database with `docker-compose up -d postgres`
- **Prevention:** Run `docker-compose up -d` before starting the app
**Error: `Port 3000 is already in use`**
- **Cause:** Another process is using port 3000
- **Solution:** Kill the process with `lsof -ti:3000 | xargs kill -9`
- **Prevention:** Configure a different port in `.env` filePrerequisites and Dependencies
Be explicit about requirements:
## Prerequisites
Before starting, ensure you have:
- **Node.js 18 or higher** - Check with `node --version`
- Download from https://nodejs.org
- Recommended: Use nvm for version management
- **PostgreSQL 14+** - Check with `psql --version`
- macOS: `brew install postgresql`
- Ubuntu: `sudo apt-get install postgresql`
- Windows: Download from https://postgresql.org/download
- **API keys** - Required for authentication
- Sign up at https://example.com/api
- Create new API key in dashboard
- Save key securely (you'll need it in setup)Configuration Documentation
Document all configuration options:
| Variable | Type | Required | Default | Description |
|---|---|---|---|---|
PORT | number | No | 3000 | Port for the server to listen on |
DATABASE_URL | string | Yes | - | PostgreSQL connection string |
NODE_ENV | enum | No | development | Environment mode (development, production, test) |
LOG_LEVEL | enum | No | info | Logging verbosity (error, warn, info, debug) |
API_KEY | string | Yes | - | Third-party API authentication key |
Include examples:
# Development
PORT=3000
DATABASE_URL=postgresql://localhost:5432/myapp_dev
NODE_ENV=development
LOG_LEVEL=debug
API_KEY=sk_test_123abc
# Production
PORT=8080
DATABASE_URL=postgresql://prod.example.com:5432/myapp
NODE_ENV=production
LOG_LEVEL=info
API_KEY=sk_live_789xyzVisual Aids
File Tree Structures
Use ASCII art for directory structures:
project/
├── src/
│ ├── components/
│ │ ├── Button.tsx # Reusable button component
│ │ └── Modal.tsx # Reusable modal component
│ ├── pages/
│ │ ├── Home.tsx # Home page component
│ │ └── About.tsx # About page component
│ └── utils/
│ └── format.ts # Formatting utilities
├── tests/
│ └── components/
│ └── Button.test.tsx # Button component tests
└── package.json # Dependencies and scriptsDiagrams
Use ASCII diagrams for flows and relationships:
Authentication Flow:
User Frontend Backend Database
| | | |
|--- Submit Credentials-->| | |
| |--- POST /auth/login -->| |
| | |--- Query User -------->|
| | |<------ User Data ------|
| | | |
| | |--- Verify Password --->|
| | |<------ Result ---------|
| | | |
| |<------ JWT Token ------| |
|<-- Login Success -------| | |
| | | |Tables for Comparisons
Use tables to compare options:
| Feature | Option A | Option B | Option C |
|---|---|---|---|
| Performance | Fast | Medium | Slow |
| Ease of use | Complex | Simple | Medium |
| Flexibility | High | Low | Medium |
| Best for | Large projects | Prototypes | Medium projects |
Accessibility
Write for Screen Readers
- Use semantic markdown headings (
#,##,###) - Provide alt text for images:
 - Use descriptive link text: ✅ "Read the API documentation" vs ❌ "Click here"
Support Multiple Learning Styles
Provide information in multiple formats:
1. Visual: Diagrams, screenshots, file trees 2. Textual: Written explanations, code comments 3. Interactive: Working examples, commands to try
Maintenance
Keep Documentation Current
Add version information:
> **Note:** This documentation is for version 2.x. For version 1.x documentation, see [v1 docs](./v1/README.md).
Last updated: 2024-01-15Mark deprecated features:
## ⚠️ Deprecated: `legacyAuth()`
**Deprecated in:** v2.0.0
**Removed in:** v3.0.0
**Alternative:** Use `modernAuth()` instead
// ❌ Old way (deprecated) await legacyAuth(token);
// ✅ New way await modernAuth(token);
Document breaking changes:
## Breaking Changes in v2.0
### Changed: Authentication method
**Before (v1.x):**auth.login(username, password);
**After (v2.x):**auth.login({ email, password });
**Migration guide:**
Replace `username` with `email` and wrap parameters in an object.Documentation Types
README Documentation
Essential sections: 1. What this does (1-2 sentences) 2. Quick start (< 5 minutes to running) 3. Project structure (visual overview) 4. Common tasks (step-by-step guides) 5. Configuration (environment variables, settings) 6. Troubleshooting (common issues) 7. Links to additional docs
Keep it focused:
- Root README should be high-level
- Link to detailed docs in subdirectories
- Aim for 500-1000 words max
Architecture Documentation
Essential sections: 1. System design (high-level overview) 2. Directory structure (detailed breakdown) 3. Data flow (how data moves through system) 4. Key design decisions (why choices were made) 5. Module dependencies (how components interact) 6. Extension points (where to add features)
Document the "why":
- Explain architectural decisions
- Provide context for choices made
- Document alternatives considered
- Note trade-offs accepted
API Documentation
Essential sections: 1. Authentication (how to authenticate) 2. Error handling (error format and codes) 3. Rate limiting (limits and headers) 4. Endpoints (all available endpoints) 5. Examples (realistic usage examples)
For each endpoint:
- What it does (plain-English explanation)
- Authentication requirements
- Request format (parameters, body)
- Response format (success and errors)
- Working example (curl or SDK)
- Common errors (what can go wrong)
Inline Code Documentation
Essential elements: 1. Purpose (why this code exists) 2. Parameters (what inputs mean) 3. Return value (what output means) 4. Examples (how to use it) 5. Edge cases (special behavior)
Comment style:
- Use standard format (JSDoc, docstrings, etc.)
- Explain "why" not "what"
- Include examples for complex functions
- Document assumptions and constraints
Testing Documentation
Test all code examples:
- Verify commands actually work
- Test setup instructions on clean environment
- Check that links aren't broken
- Validate code snippets compile/run
Make documentation testable:
<!-- Example that can be tested automatically -->npm install npm test
Expected output: All tests passed (10 tests)
Documentation Review Checklist
Before publishing documentation, verify:
Completeness:
- [ ] All required sections included
- [ ] Prerequisites clearly listed
- [ ] Setup steps are complete
- [ ] Examples are realistic and tested
- [ ] Links work correctly
Clarity:
- [ ] Written for target audience
- [ ] Technical terms defined
- [ ] Examples include context
- [ ] Success criteria clear
Accuracy:
- [ ] Code examples work
- [ ] Commands produce expected output
- [ ] Version numbers correct
- [ ] Links point to correct locations
Organization:
- [ ] Logical information flow
- [ ] Progressive disclosure used
- [ ] Related topics linked
- [ ] Visual aids where helpful
Maintenance:
- [ ] Last updated date included
- [ ] Version information noted
- [ ] Deprecated features marked
- [ ] Breaking changes documented
Anti-Patterns to Avoid
Don't assume knowledge:
- ❌ "Just use the standard approach"
- ✅ "Use dependency injection (see guide)"
Don't use vague instructions:
- ❌ "Configure the system appropriately"
- ✅ "Set
PORT=3000in your.envfile"
Don't skip error handling:
- ❌ Only show happy path examples
- ✅ Show both success and error handling
Don't leave gaps:
- ❌ "Install dependencies" → "Run the app"
- ✅ "Install dependencies" → "Configure environment" → "Run migrations" → "Run the app"
Don't use jargon without explanation:
- ❌ "Uses CRDT for eventual consistency"
- ✅ "Uses CRDT (Conflict-free Replicated Data Type) to ensure all users see the same data even when working offline"
Internationalization
Write for global audience:
- Use international date format: 2024-01-15 (not 1/15/2024)
- Avoid idioms and colloquialisms
- Use simple sentence structure
- Define acronyms on first use
Examples for clarity:
## Date Formatting
Dates should use ISO 8601 format: `YYYY-MM-DD`
Examples:
- January 15, 2024 → `2024-01-15`
- March 3, 2024 → `2024-03-03`
- December 25, 2024 → `2024-12-25`Summary
Great documentation is: 1. Accurate - Information is correct and up-to-date 2. Complete - No critical gaps in coverage 3. Clear - Easy to understand for target audience 4. Organized - Information is easy to find 5. Tested - Examples and instructions actually work 6. Maintained - Kept current as code changes 7. Accessible - Works for different learning styles 8. Actionable - Users can accomplish their goals
Documentation serves users when it:
- Gets them started quickly (< 5 minutes to success)
- Answers their questions (comprehensive coverage)
- Helps them when stuck (troubleshooting guides)
- Grows with them (beginner to advanced content)
- Stays current (regular updates and maintenance)
Visual Aids Guide
This guide provides patterns and techniques for creating effective visual aids in documentation, including diagrams, file trees, and flowcharts.
Why Visual Aids Matter
Visual aids help users:
- Understand structure - See how components fit together
- Follow flows - Trace data and process flows
- Navigate codebases - Understand directory organization
- Learn faster - Visual information is processed 60,000x faster than text
- Remember better - People remember 80% of what they see vs 20% of what they read
File Tree Structures
Basic File Tree
Use ASCII characters to show hierarchy:
project-root/
├── src/
│ ├── components/
│ ├── services/
│ └── utils/
├── tests/
├── public/
└── package.jsonCharacters to use:
├──for branches (items with siblings below)└──for last item in a list│for vertical connectionfor indentation where no connection
Annotated File Tree
Add inline comments to explain purpose:
project-root/
├── src/ # Source code
│ ├── components/ # Reusable UI components
│ │ ├── common/ # Shared components (buttons, inputs)
│ │ │ ├── Button.tsx
│ │ │ └── Input.tsx
│ │ └── features/ # Feature-specific components
│ │ ├── auth/ # Authentication components
│ │ └── dashboard/ # Dashboard components
│ ├── services/ # Business logic and API calls
│ │ ├── api.ts # API client configuration
│ │ └── auth.ts # Authentication service
│ ├── utils/ # Helper functions
│ │ └── format.ts # Formatting utilities
│ └── index.tsx # Application entry point
├── tests/ # Test files (mirrors src/)
│ └── components/
│ └── Button.test.tsx
├── public/ # Static assets (images, fonts)
│ ├── images/
│ └── fonts/
├── .env.example # Environment variable template
├── package.json # Dependencies and scripts
└── README.md # Project documentationFile Tree with File Sizes
Show relative importance or complexity:
project-root/
├── src/ [12 files, 5,200 lines]
│ ├── components/ [8 files, 3,800 lines] ← Most of the code
│ ├── services/ [3 files, 1,200 lines]
│ └── utils/ [1 file, 200 lines]
├── tests/ [8 files, 2,100 lines]
└── config/ [3 files, 150 lines]File Tree with Change Indicators
Show what's new or modified:
project-root/
├── src/
│ ├── components/
│ │ ├── Button.tsx ← Modified for v2.0
│ │ └── Modal.tsx ✨ New in v2.0
│ └── services/
│ └── legacy.ts ⚠️ Deprecated, use auth.ts instead
└── README.md ← Updated installation stepsSystem Architecture Diagrams
Component Diagram
Show how major pieces fit together:
┌─────────────────────────────────────────────────────────┐
│ Application │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────┐ │
│ │ Frontend │ │ Backend │ │ Database│ │
│ │ (React) │◄────►│ (Node.js) │◄────►│(Postgres│ │
│ └─────────────┘ └─────────────┘ └─────────┘ │
│ │ │ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Browser │ │ File Store │ │
│ │ Storage │ │ (S3) │ │
│ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────┘Symbols:
┌─┐│└─┘- Boxes for components◄────►- Bidirectional communication────►- Unidirectional flow▼- Downward dependency
Layered Architecture
Show architectural layers:
┌───────────────────────────────────────┐
│ Presentation Layer │ ← User Interface
│ (React Components, Pages) │
├───────────────────────────────────────┤
│ Application Layer │ ← Business Logic
│ (Services, State Management) │
├───────────────────────────────────────┤
│ Data Access Layer │ ← Database Operations
│ (Repositories, ORMs, APIs) │
├───────────────────────────────────────┤
│ Infrastructure Layer │ ← External Services
│ (Database, Cache, Message Queue) │
└───────────────────────────────────────┘Network Architecture
Show how services communicate:
Internet
│
▼
┌─────────────────┐
│ Load Balancer │
└────────┬────────┘
│
┌────┴────┐
│ │
▼ ▼
┌────────┐ ┌────────┐
│ Web │ │ Web │
│ Server │ │ Server │
│ #1 │ │ #2 │
└───┬────┘ └───┬────┘
│ │
└────┬─────┘
▼
┌──────────┐
│ API │
│ Server │
└────┬─────┘
│
┌────┴─────┐
│ │
▼ ▼
┌──────┐ ┌───────┐
│ DB │ │ Cache │
│(Primary) │(Redis)│
└──────┘ └───────┘Data Flow Diagrams
Linear Flow
Show a simple sequence:
User Input → Validation → Processing → Storage → Response
[1] Form Submit → [2] Check Data → [3] Transform → [4] Save → [5] SuccessBranching Flow
Show conditional logic:
User Login Attempt
│
▼
Check Credentials
│
┌────┴────┐
│ │
▼ ▼
Valid? Invalid?
│ │
│ ▼
│ Show Error
│ │
│ ▼
│ Retry Count++
│ │
▼ ▼
Generate Max Retries?
Token │
│ ┌────┴────┐
│ ▼ ▼
│ Yes No
│ │ │
│ ▼ └──► Return to Check
│ Lock
│ Account
│
▼
Return TokenDetailed Step Flow
Show exactly where things happen in code:
User Registration Flow:
[1] User submits form
└─► components/RegistrationForm.tsx: handleSubmit()
[2] Validate input
└─► utils/validation.ts: validateRegistrationData()
[3] Check email uniqueness
└─► services/user.ts: checkEmailExists()
└─► Makes API call: GET /api/users?email={email}
[4] Create user account
└─► services/user.ts: createUser()
└─► Makes API call: POST /api/users
└─► Backend: api/users/route.ts: POST handler
└─► Database: INSERT INTO users
[5] Send welcome email
└─► services/email.ts: sendWelcomeEmail()
└─► External API: Sendgrid
[6] Update UI with success
└─► components/RegistrationForm.tsx: setState({success: true})Sequence Diagram
Show interactions over time:
User Frontend Backend Database
│ │ │ │
│─── Click ─────►│ │ │
│ │ │ │
│ │─── GET /api/data ──►│ │
│ │ │ │
│ │ │─── SELECT * ─────►│
│ │ │ │
│ │ │◄─── Results ──────│
│ │ │ │
│ │◄─── JSON Response ──│ │
│ │ │ │
│◄─── Display ───│ │ │
│ │ │ │State Diagrams
Show state transitions:
Order State Machine:
┌─────────┐
│ Created │ ← Initial state
└────┬────┘
│
│ User clicks "Pay"
▼
┌──────────┐
│ Pending │
│ Payment │
└─────┬────┘
│
┌────┴────┐
│ │
│ │ Payment fails
▼ ▼
┌────────┐ ┌──────────┐
│ Paid │ │ Cancelled│ ← Terminal states
└───┬────┘ └──────────┘
│
│ Items shipped
▼
┌───────────┐
│ Fulfilled │ ← Terminal state
└───────────┘Database Schema Diagrams
Entity Relationship
Show table relationships:
┌──────────────┐ ┌──────────────┐
│ users │ │ posts │
├──────────────┤ ├──────────────┤
│ id (PK) │────┐ │ id (PK) │
│ email │ │ │ user_id (FK) │────┐
│ name │ └───►│ title │ │
│ created_at │ │ content │ │
└──────────────┘ │ created_at │ │
└──────────────┘ │
│
┌──────────────┐ │
│ comments │ │
├──────────────┤ │
│ id (PK) │ │
│ post_id (FK) │◄───┘
│ user_id (FK) │
│ content │
│ created_at │
└──────────────┘
Relationships:
- User has many Posts (1:N)
- Post has many Comments (1:N)
- User has many Comments (1:N)Simple Table View
users table:
┌────┬──────────────────┬──────────┬────────────┐
│ id │ email │ name │ role │
├────┼──────────────────┼──────────┼────────────┤
│ 1 │ alice@example.com│ Alice │ admin │
│ 2 │ bob@example.com │ Bob │ user │
│ 3 │ carol@example.com│ Carol │ user │
└────┴──────────────────┴──────────┴────────────┘API Request/Response Flows
REST API Flow
Client Server Database
│ │ │
│ GET /api/users/123 │ │
├──────────────────────────────►│ │
│ │ │
│ │ SELECT * FROM users │
│ │ WHERE id = 123 │
│ ├─────────────────────────────►│
│ │ │
│ │ User data │
│ │◄─────────────────────────────┤
│ │ │
│ 200 OK │ │
│ {user data} │ │
│◄──────────────────────────────┤ │
│ │ │Process Flowcharts
Decision Tree
Start
│
▼
┌────────────────┐
│ User logged in?│
└────────┬───────┘
│
┌─────────┴─────────┐
│ │
Yes No
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Show │ │ Redirect to │
│ Dashboard │ │ Login Page │
└──────┬───────┘ └──────────────┘
│
▼
┌──────────────┐
│ Has premium? │
└──────┬───────┘
│
┌──────┴──────┐
│ │
Yes No
│ │
▼ ▼
┌────────┐ ┌────────┐
│ Show │ │ Show │
│ All │ │ Basic │
│Features│ │Features│
└────────┘ └────────┘Module Dependency Graphs
Simple Dependencies
pages/
│
└─► components/
│
├─► hooks/
│ │
│ └─► services/
│ │
│ └─► utils/
│
└─► utils/Complex Dependencies
┌──────────┐
│ pages/ │
└────┬─────┘
│
┌───────────┼───────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│components│ │ hooks/ │ │ services/│
└─────┬────┘ └─────┬────┘ └─────┬────┘
│ │ │
└────────┬───┴────┬───────┘
▼ ▼
┌────────────────┐
│ utils/ │
└────────────────┘
Legend:
─────► Direct dependencyTimeline Diagrams
Project Timeline
Q1 2024 Q2 2024 Q3 2024 Q4 2024
───┼───────────────────┼───────────────────┼───────────────────┼─────►
│ │ │ │
├─ v1.0 Release ├─ v1.5 Release ├─ v2.0 Release ├─ v2.5
│ • Basic features │ • API v2 │ • New UI │ • Mobile
│ • Core API │ • Performance │ • Webhooks │ • Plugins
│ │ │ │Development Phases
Phase 1: Planning Phase 2: Development Phase 3: Testing Phase 4: Launch
─────────────────────────────────────────────────────────────────────────────►
2 weeks 6 weeks 3 weeks 1 week
│◄────────────►│◄───────────────────────────►│◄──────────────►│◄──────────►│
│ │ │ │ │
│ • Research │ • Feature development │ • QA testing │ • Deploy │
│ • Design │ • Code review │ • Bug fixes │ • Monitor │
│ • Planning │ • Unit tests │ • UAT │ • Support │Comparison Tables
Feature Matrix
┌─────────────┬──────────┬──────────┬──────────┐
│ Feature │ Plan A │ Plan B │ Plan C │
├─────────────┼──────────┼──────────┼──────────┤
│ Storage │ 10 GB │ 100 GB │ 1 TB │
│ Users │ 5 │ 25 │ Unlimited│
│ API Calls │ 1,000/mo │ 10,000/mo│ Unlimited│
│ Support │ Email │ Email │ 24/7 │
│ Price/month │ $10 │ $50 │ $200 │
└─────────────┴──────────┴──────────┴──────────┘Technology Comparison
┌────────────┬─────────┬─────────┬─────────┬─────────┐
│ Criteria │ React │ Vue │ Angular │ Svelte │
├────────────┼─────────┼─────────┼─────────┼─────────┤
│ Simplicity │ ★★★☆☆ │ ★★★★☆ │ ★★☆☆☆ │ ★★★★★ │
│ Performance│ ★★★★☆ │ ★★★★☆ │ ★★★☆☆ │ ★★★★★ │
│ Ecosystem │ ★★★★★ │ ★★★★☆ │ ★★★★☆ │ ★★★☆☆ │
│ Jobs │ ★★★★★ │ ★★★★☆ │ ★★★★☆ │ ★★☆☆☆ │
└────────────┴─────────┴─────────┴─────────┴─────────┘Best Practices
Choose the Right Visual
| When you need to show... | Use... |
|---|---|
| Code organization | File tree structure |
| System components | Architecture diagram |
| Process steps | Flow diagram or sequence diagram |
| Data movement | Data flow diagram |
| Conditional logic | Decision tree or flowchart |
| State changes | State diagram |
| Database structure | ER diagram |
| Module relationships | Dependency graph |
| Time-based changes | Timeline or Gantt chart |
| Feature comparison | Table or matrix |
Keep It Simple
- One concept per diagram - Don't try to show everything
- Limit complexity - 5-7 items per diagram is ideal
- Use consistent symbols - Don't invent new notation
- Label clearly - Every box and arrow should be labeled
- Add legends - Explain any symbols used
Make It Accessible
- Use text descriptions - Describe what the diagram shows
- Provide alt text - For accessibility tools
- Use semantic formatting - Code blocks for ASCII diagrams
- High contrast - Ensure diagrams are readable
- Consider text-only - Some readers can't see diagrams
Test Your Visuals
- Show to someone unfamiliar - Can they understand it?
- Print it out - Does it work on paper?
- View on mobile - Is it readable on small screens?
- Test with screen readers - Is the content accessible?
Tools for Creating Diagrams
ASCII Art (Recommended for Documentation)
Pros:
- Works in any text editor
- Version control friendly
- Always renders correctly
- Accessible to screen readers
Cons:
- Time-consuming to create
- Limited visual appeal
- Hard to create complex diagrams
When to use: For simple diagrams in markdown documentation
Mermaid (Code-Based Diagrams)
graph TD
A[Start] --> B{Is it working?}
B -->|Yes| C[Great!]
B -->|No| D[Debug]
D --> APros:
- Text-based (version control friendly)
- Renders as nice graphics
- Supports many diagram types
Cons:
- Requires Mermaid renderer
- Learning curve for syntax
- Not all platforms support it
When to use: When your documentation platform supports Mermaid
Draw.io / Lucidchart (Visual Tools)
Pros:
- Professional appearance
- Easy to create complex diagrams
- Many templates available
Cons:
- Binary files (not version control friendly)
- Requires separate tool
- Can become outdated
When to use: For complex diagrams or presentations
Examples from Real Projects
React Component Hierarchy
App
├── Header
│ ├── Logo
│ ├── Navigation
│ │ ├── NavItem
│ │ └── NavItem
│ └── UserMenu
├── Sidebar
│ ├── SidebarItem
│ └── SidebarItem
└── Content
├── Dashboard
│ ├── StatsCard
│ ├── Chart
│ └── RecentActivity
└── FooterAuthentication Flow
1. User visits protected page
└─► Check if token exists in localStorage
2. Token exists?
├─► YES: Validate token
│ └─► Valid?
│ ├─► YES: Allow access
│ └─► NO: Redirect to login (expired token)
│
└─► NO: Redirect to login (not authenticated)
3. User logs in
└─► POST /api/auth/login {email, password}
└─► Success?
├─► YES: Store token in localStorage → Redirect to original page
└─► NO: Show error message → Stay on login pageSummary
Effective visual aids:
- Clarify complex concepts faster than text alone
- Show relationships between components
- Guide users through processes and flows
- Organize information spatially
- Improve retention of information
Choose diagrams that:
- Match the concept being explained
- Stay simple and focused
- Use consistent notation
- Are accessible to all users
- Complement text rather than replace it