25/04/2026 02:48am

Code Documentation: How to Write Documentation That Developers Actually Want to Read
#Software Engineering Documentation
#Software Documentation
#API Documentation
#Code Documentation
Writing good documentation is one of the most important skills for programmers, yet it's something many people often skip or do superficially. The result is that when colleagues read the code, or even when we ourselves return to look at old code after just a few months, we're confused about what we wrote. This article will teach techniques for writing documentation that makes your code easy to understand, maintainable, and enables teams to work efficiently.
Why Is Code Documentation Important?
Problems Caused by Lack of Documentation
When there's no good documentation, development teams waste time guessing how code sections work. Debugging becomes more difficult, onboarding new members takes longer than it should, and worst of all, knowledge is lost when the code author leaves the team.
Lack of documentation also causes technical debt to accumulate because others don't dare modify code they don't understand, causing systems to gradually deteriorate over time.
Benefits of Good Documentation
Good documentation reduces time needed to understand code, increases confidence in making changes, and makes code reviews more effective. It also helps in planning and designing new features because teams understand the structure and principles of existing systems.
Types of Code Documentation
Inline Comments: Explaining Within Code
Comments within code should explain "why" more than "what" because the code itself should be able to explain what it does. Good comments explain the reasoning behind decisions, problem context, or important precautions.
// Bad: Explaining what the code already does
let total = price * quantity; // Multiply price by quantity
// Good: Explaining reasoning and context
let total = price * quantity; // Excluding VAT because foreign customers receive exemption
Function and Method Documentation
Writing docstrings or JSDoc for functions should specify purpose, input parameters, return values, and possible side effects.
/**
* Calculate discount for VIP customers
* @param {number} originalPrice - Original price before discount
* @param {string} customerTier - Customer level (bronze, silver, gold, platinum)
* @param {boolean} isFirstPurchase - Whether this is first purchase
* @returns {number} Price after discount
* @throws {Error} When customerTier is invalid
*/
function calculateVIPDiscount(originalPrice, customerTier, isFirstPurchase) {
// Implementation here
}
API Documentation
For API endpoints, there should be descriptions of URLs, HTTP methods, request/response formats, error codes, and usage examples. Using tools like Swagger/OpenAPI helps create standardized and testable documentation.
README and Project-level Documentation
README is the first page people read. It should include installation information, basic usage, project structure, and contribution guidelines. For complex projects, additional architecture documents or technical specifications may be needed.
Principles of Effective Documentation Writing
Clarity and Conciseness
Use easily understandable language, avoid unnecessarily complex technical terms, write concisely but comprehensively, and use organized structure. Breaking into subsections and using bullet points makes reading easier.
Using Examples and Code Snippets
Good examples are worth more than lengthy explanations. Provide code snippets that actually work and cover important use cases. Should include both normal usage examples and edge cases.
// Normal usage example
const discount = calculateVIPDiscount(1000, 'gold', false); // Returns: 850
// Edge case example
const newCustomerDiscount = calculateVIPDiscount(1000, 'bronze', true); // Returns: 900
Keeping Up-to-Date
Outdated documentation is worse than no documentation because it causes misunderstandings. There should be processes for updating documentation when code changes.
Tools and Best Practices
Tools for Creating Documentation
JSDoc for JavaScript, Sphinx for Python, JavaDoc for Java are tools that help create documentation from code comments. For API documentation, there's Swagger/OpenAPI, Postman, or Insomnia.
For project documentation, you can use GitBook, Notion, or even Markdown files in the repository. The important thing is choosing tools the team can use conveniently and maintain easily.
Documentation as Code
Storing documentation in the same repository as code helps keep them synced easily and allows reviewing documentation through pull requests like code.
Automated Documentation Generation
Use tools that automatically create documentation from code annotations, such as generating API docs from OpenAPI specs or generating code documentation from docstrings.
Examples of Good Documentation
Function Documentation Example
def process_payment(amount, payment_method, customer_id):
"""
Process payment for customer
This function validates customer information, calculates fees,
and charges the account or credit card
Args:
amount (float): Amount to be paid (baht)
payment_method (str): Payment method ('credit_card', 'bank_transfer', 'wallet')
customer_id (int): Customer ID
Returns:
dict: Transaction result
- success (bool): Whether successful
- transaction_id (str): Reference ID
- fee (float): Fee charged
Raises:
ValueError: When amount is less than or equal to 0
CustomerNotFoundError: When customer data not found
PaymentFailedError: When payment fails
Example:
>>> result = process_payment(1000.0, 'credit_card', 12345)
>>> print(result['success'])
True
>>> print(result['transaction_id'])
'TXN_20231201_001'
"""
README Structure Example
# E-commerce API Project
## Description
API for e-commerce system supporting product management, orders, and payments
## Installation
### System Requirements
- Node.js 16+
- MongoDB 5.0+
- Redis 6.0+
### Installation Steps
1. Clone repository
2. Install dependencies: `npm install`
3. Copy config file: `cp .env.example .env`
4. Run database: `docker-compose up -d`
5. Start server: `npm start`
## Usage
### API Endpoints
- GET `/api/products` - Get product list
- POST `/api/orders` - Create new order
- GET `/api/orders/:id` - View order details
### Usage Example
```bash
curl -X GET "http://localhost:3000/api/products?category=electronics&limit=10"
Project Structure
src/
├── controllers/ # API controllers
├── models/ # Database models
├── routes/ # Route definitions
├── middleware/ # Middleware functions
└── utils/ # Helper functions
Development
- Run tests:
npm test - Check code style:
npm run lint - Generate documentation:
npm run docs
Mistakes to Avoid
Writing Useless Comments
Avoid writing comments that explain what the code already clearly does, such as `i++; // increment i` or comments that don't provide additional information.
Outdated Documentation
Not updating documentation when code changes causes confusion and misunderstandings. There should be processes for keeping documentation current.
Writing Too Long
Documentation that's unnecessarily long makes people not want to read it. Should write concisely but comprehensively, and divide into readable sections.
Lack of Context
Explaining only technical details without business context or design reasoning makes readers not understand the big picture.
Creating Documentation Culture in Teams
Establishing Standards and Practices
Create clear documentation guidelines for the team. Define writing formats, tools used, and each person's responsibilities.
Code Review and Documentation Review
Include documentation review in the code review process. Check that documentation is correct, complete, and current.
Providing Feedback and Improvement
Create channels for teams to express opinions about documentation and continuously improve. Learn from experience and mistakes that occur.
Advanced Documentation Techniques
Interactive Documentation
Create documentation with interactive elements such as API testing within documentation pages or code playgrounds where readers can experiment.
Visual Documentation
Use diagrams, flowcharts, or screenshots to help explain complex concepts. Tools like Mermaid, Draw.io, or Lucidchart can help create visual documentation.
Documentation Testing
Test whether code examples in documentation still work. May use automated testing tools to verify documentation accuracy.
Measuring Documentation Effectiveness
Metrics to Track
Track how long teams take to understand new code, whether questions about well-documented code decrease, and team satisfaction with documentation quality.
Gathering Feedback
Survey team opinions about understanding and benefits of documentation. Use this data for improvement and development.
Summary: Writing Good Documentation Is a Long-term Investment
Writing good documentation isn't easy, but it's a worthwhile long-term investment. It helps reduce code maintenance costs, increases team efficiency, and makes software development higher quality.
The important thing is starting with the mindset that documentation is part of the code, not something added later. Creating habits of writing documentation alongside code will make both code and documentation progressively better quality.
Remember that the best documentation is what makes others (including our future selves) understand code quickly and correctly. Taking time to write documentation today will save time for everyone on the team in the future.
🔵 Facebook: Superdev School (Superdev)
📸 Instagram: superdevschool
🎬 TikTok: superdevschool
🌐 Website: www.superdev.school