Netspective Logo

Documentation Guidelines

Standards for creating and maintaining technical documentation

Documentation is a critical deliverable for regulated software development. Good documentation enables knowledge transfer, supports compliance audits, and ensures systems can be maintained over time.

Documentation Principles

PrincipleDescription
AccurateDocumentation reflects the actual system state
CompleteAll required information is present
CurrentUpdated as the system changes
AccessibleEasy to find and understand
TraceableLinks to requirements, code, and tests

Documentation Types

Documentation Hierarchy

Document Categories

CategoryPurposeAudience
RequirementsDefine what the system must doStakeholders, Developers
ArchitectureHigh-level system designArchitects, Tech Leads
DesignDetailed component designDevelopers
APIInterface specificationsIntegrators, Developers
UserEnd-user instructionsUsers, Support
OperationsSystem administrationOperations, Support
ComplianceRegulatory evidenceAuditors, QA

Code Documentation

Inline Comments

// Comments should explain WHY, not WHAT

// Bad: Describes what the code does (obvious from reading it)
// Increment counter by 1
counter++;

// Good: Explains why this approach was chosen
// Use exponential backoff to avoid overwhelming the server
// during recovery from failures
const delay = Math.pow(2, retryCount) * baseDelayMs;

// Good: Explains a non-obvious business rule
// Tax exempt if customer is a registered non-profit
// See requirement REQ-TAX-001
if (customer.nonprofitStatus === 'verified') {
  return 0;
}

Function Documentation

/**
 * Calculates the total price for an order including taxes and discounts.
 *
 * @description Applies discounts first, then calculates tax on the
 * discounted amount. Rounds to 2 decimal places for currency precision.
 *
 * @param items - Line items in the order
 * @param discountCode - Optional promotional discount code
 * @param taxRate - Tax rate as decimal (e.g., 0.08 for 8%)
 * @returns Total price including tax, or null if calculation fails
 *
 * @example
 * const total = calculateOrderTotal(
 *   [{ price: 100, quantity: 2 }],
 *   'SAVE10',
 *   0.08
 * );
 * // Returns: 194.40 (200 - 10% discount = 180 + 8% tax)
 *
 * @throws {ValidationError} If items array is empty
 * @see REQ-PRICING-001 for business rules
 */
function calculateOrderTotal(
  items: OrderItem[],
  discountCode?: string,
  taxRate: number = 0
): number | null {
  // Implementation
}

Module Documentation

/**
 * @module PaymentProcessor
 *
 * @description
 * Handles all payment processing operations including credit card
 * transactions, refunds, and payment verification.
 *
 * ## Architecture
 * This module integrates with external payment gateways through
 * a provider abstraction layer, allowing different providers
 * to be used without changing business logic.
 *
 * ## Security
 * - No card numbers are stored locally
 * - All data encrypted in transit (TLS 1.3)
 * - PCI DSS compliant
 *
 * ## Dependencies
 * - PaymentGateway: External payment provider interface
 * - AuditLogger: Compliance logging service
 *
 * @see docs/architecture/payment-flow.md
 */

API Documentation

OpenAPI Specification

openapi: 3.0.3
info:
  title: Order Management API
  description: |
    API for managing customer orders in the e-commerce platform.

    ## Authentication
    All endpoints require Bearer token authentication.

    ## Rate Limiting
    - 100 requests per minute per API key
    - 429 response when exceeded
  version: 1.0.0

paths:
  /orders:
    post:
      summary: Create a new order
      description: |
        Creates a new order for the authenticated customer.
        Validates inventory availability before accepting.
      operationId: createOrder
      tags:
        - Orders
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateOrderRequest'
            example:
              items:
                - productId: "prod-123"
                  quantity: 2
              shippingAddress:
                street: "123 Main St"
                city: "Seattle"
                state: "WA"
                zipCode: "98101"
      responses:
        '201':
          description: Order created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
        '400':
          description: Invalid request
        '409':
          description: Inventory not available

Architecture Documentation

Architecture Decision Records (ADRs)

# ADR-001: Use PostgreSQL for Primary Database

## Status
Accepted

## Context
We need to select a primary database for the order management system.
Requirements include:
- ACID compliance for financial transactions
- Support for complex queries and reporting
- Horizontal read scaling capability
- Strong ecosystem and community support

## Decision
We will use PostgreSQL as our primary database.

## Consequences

### Positive
- Mature, well-documented technology
- Excellent JSON support for flexible schemas
- Strong transaction guarantees
- Rich extension ecosystem (PostGIS, TimescaleDB)

### Negative
- Vertical scaling limits for writes
- More complex to operate than managed NoSQL options

### Mitigation
- Use read replicas for reporting queries
- Implement caching layer for frequently accessed data

## Related
- REQ-DATA-001: Data integrity requirements
- ADR-003: Caching strategy

System Diagrams

Use standard notation for diagrams:

Diagram TypePurposeFormat
ContextSystem boundaries and external actorsC4 Level 1
ContainerHigh-level technology choicesC4 Level 2
ComponentInternal structure of containersC4 Level 3
SequenceRuntime behavior and flowsUML
ER DiagramData model relationshipsUML/ERD

Operational Documentation

Runbook Structure

# Service: Order Processing Service

## Overview
Handles order creation, validation, and fulfillment coordination.

## Health Checks
- **Endpoint**: `/health`
- **Expected**: HTTP 200 with `{"status": "healthy"}`
- **Timeout**: 5 seconds

## Dependencies
| Service | Purpose | Criticality |
|---------|---------|-------------|
| PostgreSQL | Order storage | Critical |
| Payment API | Payment processing | Critical |
| Inventory API | Stock validation | High |
| Email Service | Notifications | Low |

## Common Issues

### Issue: High Latency
**Symptoms**: Response times > 2 seconds
**Investigation**:
1. Check database connection pool (`/metrics`)
2. Review slow query logs
3. Check downstream service health

**Resolution**:
- If connection pool exhausted: Restart service
- If slow queries: Escalate to DBA

### Issue: Payment Failures
**Symptoms**: Increased 500 errors on /orders endpoint
**Investigation**:
1. Check payment gateway status
2. Review payment service logs
3. Verify API credentials

**Resolution**:
- If gateway down: Enable fallback provider
- If credential issue: Rotate and update secrets

Compliance Documentation

Design History File (DHF)

For FDA-regulated software:

DocumentContentUpdate Frequency
Requirements SpecFunctional and safety requirementsPer change
Design SpecArchitecture and detailed designPer change
Verification ReportTest results against requirementsPer release
Validation ReportUser acceptance testing resultsPer release
Traceability MatrixRequirements to tests mappingPer change
Risk AnalysisFMEA, hazard analysisPer change

Traceability Matrix Example

RequirementDesignCodeTestRisk
REQ-001: Vital signs displaySDS-001VitalDisplay.tsTC-001, TC-002R-001
REQ-002: Alarm thresholdsSDS-002AlarmService.tsTC-003, TC-004R-002
REQ-003: Data loggingSDS-003DataLogger.tsTC-005R-003

Documentation Tools

PurposeToolNotes
API DocsOpenAPI/SwaggerGenerated from code
Code DocsTSDoc, JSDoc, SphinxIntegrated with IDE
ArchitectureMarkdown + MermaidVersion controlled
RunbooksMarkdownIn repository
User DocsDocusaurus, FumadocsSearchable, versioned

Documentation as Code

# docs/mkdocs.yml
site_name: Project Documentation
nav:
  - Home: index.md
  - Architecture:
    - Overview: architecture/overview.md
    - Decisions: architecture/decisions/
  - API Reference: api/
  - Operations:
    - Runbooks: ops/runbooks/
    - Incidents: ops/incidents/

plugins:
  - search
  - mermaid2
  - git-revision-date

Best Practices

Do

  • Keep documentation close to code (in same repository)
  • Automate generation where possible
  • Review documentation in PRs
  • Use templates for consistency
  • Include diagrams for complex concepts
  • Date and version all documents

Don't

  • Let documentation become stale
  • Duplicate information (link instead)
  • Write documentation for documentation's sake
  • Use jargon without explanation
  • Assume reader context
  • Skip documentation for "simple" features


Compliance

This section fulfills ISO 13485 requirements for documentation requirements (4.2), control of documents (4.2.3), and control of records (4.2.4), and ISO 27001 requirements for documented information (7.5), operating procedures documentation (A.5.37), and information security documentation (5.2).

View full compliance matrix

How is this guide?

Last updated on

On this page