Comments and Documentation
Comments and Documentation
Learn how to write useful comments and documentation that help developers understand, maintain, debug, and improve software projects.
Introduction
Comments and documentation are important parts of professional software development.
Code tells the computer what to do, but comments and documentation help humans understand the purpose, logic, usage, limitations, and decisions behind the code.
Beginners often think that comments mean writing explanations for every line of code. But professional developers use comments carefully. The goal is not to comment more, but to comment meaningfully.
Easy Real-Life Example
Comments and Documentation as a Map Guide
Imagine visiting a large museum. The rooms, paintings, and pathways are already there, but signs and guide notes help visitors understand where to go and why certain exhibits are important.
Museum:
Rooms and exhibits → Actual code
Direction signs → Comments
Visitor guidebook → Documentation
Important explanations → Design notes or API docs
Programming:
Code → Performs the task
Comments → Explain tricky or important parts
Documentation → Explains how to use, maintain, or understand the project
Comments and documentation should guide the reader without creating unnecessary noise.
What are Comments?
Comments are human-readable notes written inside source code.
Comments are ignored by the compiler or interpreter. They do not affect program execution.
Example Comment
/*
This comment explains why a maximum retry limit is used.
*/
MAX_RETRY_COUNT = 3
The program uses the value, but the comment helps the developer understand the reason behind the decision.
What is Documentation?
Documentation is written information that explains how software works, how to use it, how to maintain it, or how different parts of the system are designed.
Documentation can be written inside code, in README files, in user manuals, in API documents, in architecture documents, or in knowledge base articles.
Common documentation examples:
- README file
- API documentation
- Function documentation
- Setup guide
- User manual
- Architecture document
- Database design document
- Troubleshooting guide
- Release notes
Comments vs Documentation
Comments and documentation are related, but they are not exactly the same.
| Aspect | Comments | Documentation |
|---|---|---|
| Location | Inside source code. | Inside code or separate files/documents. |
| Purpose | Explain specific code logic or decisions. | Explain project usage, structure, setup, APIs, or design. |
| Audience | Mostly developers. | Developers, testers, users, support teams, stakeholders. |
| Example | Comment explaining a complex formula. | README explaining how to run the project. |
Why Comments and Documentation are Important
Software is often maintained for months or years. Developers may leave a project, new developers may join, and old code may need updates.
Good comments and documentation help people understand the software faster.
Benefits
- Help developers understand complex logic.
- Explain the reason behind important decisions.
- Make maintenance easier.
- Help new team members understand the project.
- Improve collaboration in team projects.
- Support debugging and troubleshooting.
- Explain how to use functions, modules, APIs, or systems.
- Reduce dependency on one person’s memory.
- Help testers understand expected behavior.
- Make projects more professional and long-lasting.
Important Rule: Code First, Comments Second
Before adding comments, developers should try to make the code itself readable.
Meaningful names, small functions, clear structure, and simple logic reduce the need for too many comments.
Poor Code with Comment
// Calculate final price
x = a - b + c
The comment helps a little, but the variable names are still unclear.
Better Self-Explanatory Code
finalPrice = subtotal - discountAmount + taxAmount
This version does not need a comment because the names already explain the logic.
Types of Comments
Comments can be used in different ways depending on the purpose.
| Comment Type | Purpose | Example Use |
|---|---|---|
| Single-line comment | Short explanation or note. | Explain one important line or decision. |
| Multi-line comment | Longer explanation. | Explain complex algorithm or business rule. |
| Inline comment | Small note near a line of code. | Explain unusual value or condition. |
| Documentation comment | Formal description of function/class/module. | Describe parameters, return value, and usage. |
| TODO comment | Marks future work. | Reminder to improve or complete something. |
| Warning comment | Warns about important consequences. | Explain why a risky change should be avoided. |
Good Comments
Good comments add useful information that the code alone does not clearly show.
Good Comments Usually Explain
- Why a decision was made.
- Why a special case exists.
- What business rule is being applied.
- What assumption is being used.
- What limitation or risk exists.
- What future task is pending.
- How a public function or API should be used.
Good Comment Example
// Apply discount before tax because business rules calculate tax on discounted amount.
discountedAmount = subtotal - discountAmount
taxAmount = discountedAmount * taxRate
This comment explains the reason behind the calculation order.
Bad Comments
Bad comments repeat obvious code, become outdated, mislead readers, or add unnecessary noise.
Bad Comment Types
- Comments that repeat exactly what the code already says.
- Outdated comments that no longer match the code.
- Misleading comments.
- Comments used instead of fixing unclear code.
- Large blocks of commented-out old code.
- Comments that only the original author understands.
- Unnecessary comments on every line.
Bad Comment Example
// Add 1 to count
count = count + 1
This comment is unnecessary because the code is already clear.
Example: Poor Comments vs Better Comments
Poor Version
// Set price
price = 1000
// Set discount
discount = 100
// Subtract discount from price
finalAmount = price - discount
These comments mostly repeat the code.
Better Version
price = 1000
discount = 100
// Promotional discount is applied directly before calculating tax.
finalAmount = price - discount
The improved comment explains a useful business reason.
Documentation Comments / Docstrings
Documentation comments, sometimes called docstrings or docblocks, describe functions, classes, methods, modules, or APIs in a structured way.
They commonly explain what a function does, what input it accepts, what output it returns, and any important conditions.
Language-Neutral Docstring Example
/*
Function: calculateFinalAmount
Purpose:
Calculates the final payable amount after applying discount and tax.
Inputs:
- subtotal: original amount before discount
- discountAmount: amount to subtract
- taxRate: tax percentage to apply
Output:
- final payable amount
Notes:
Tax is calculated after discount.
*/
FUNCTION calculateFinalAmount(subtotal, discountAmount, taxRate)
discountedAmount = subtotal - discountAmount
taxAmount = discountedAmount * taxRate / 100
RETURN discountedAmount + taxAmount
END FUNCTION
This type of documentation is useful when a function is reused by many developers.
What Should Function Documentation Include?
Function documentation should be short but complete enough to help others use the function correctly.
| Item | Meaning | Example |
|---|---|---|
| Purpose | What the function does. | Calculates average marks. |
| Parameters | What inputs are required. | marksList contains marks values. |
| Return value | What output is returned. | Returns average as number. |
| Assumptions | Conditions expected by the function. | Marks should be between 0 and 100. |
| Errors | What can go wrong. | Empty marks list is invalid. |
| Example usage | How to call the function. | calculateAverage([80, 90, 70]) |
README Documentation
A README file explains the project at a high level.
It is usually the first document a developer reads when opening a project.
README Usually Includes
- Project name.
- Project purpose.
- Features.
- Setup instructions.
- How to run the project.
- How to test the project.
- Folder structure.
- Configuration details.
- Common problems and solutions.
- Contribution guidelines.
Simple README Structure
Project Name:
Student Marks Management System
Purpose:
This project helps teachers store marks and generate student reports.
Features:
- Add students
- Enter marks
- Calculate average
- Generate result
How to Run:
1. Install required tools.
2. Open the project folder.
3. Run the application.
Folder Structure:
- src
- tests
- docs
- config
API Documentation
API documentation explains how other programs or developers can use an API.
It should describe endpoints, inputs, outputs, status codes, authentication rules, and examples.
API: Create Student
Endpoint:
POST /students
Input:
name, rollNumber, className, section
Success Output:
Student record created successfully.
Error Cases:
- Roll number already exists
- Required field missing
- Unauthorized request
API documentation is important when frontend, backend, mobile, or external teams need to integrate with the system.
Architecture Documentation
Architecture documentation explains how the system is structured.
It helps developers understand major components, data flow, dependencies, and deployment structure.
Architecture Documentation May Explain:
- System overview
- Main modules
- Database design
- External services
- API communication
- Authentication flow
- Deployment environment
- Security considerations
- Performance considerations
Comments for Business Rules
Sometimes code follows a business rule that may not be obvious.
In such cases, comments help explain the reason.
// Students must score at least 40 in each subject to pass,
// even if their average marks are above 40.
IF mathMarks >= 40 AND scienceMarks >= 40 AND englishMarks >= 40 THEN
result = "Pass"
ELSE
result = "Fail"
END IF
The comment explains an important rule that may not be clear from the condition alone.
Warning Comments
Warning comments are useful when changing a piece of code can create unexpected problems.
// Do not change this order.
// Tax calculation depends on discount being applied first.
discountedAmount = subtotal - discountAmount
taxAmount = discountedAmount * taxRate / 100
Warning comments should be used carefully and only when the risk is real.
TODO Comments
TODO comments mark work that needs to be completed later.
// TODO: Add validation for negative marks.
FUNCTION calculateGrade(marks)
IF marks >= 40 THEN
RETURN "Pass"
ELSE
RETURN "Fail"
END IF
END FUNCTION
TODO comments are useful, but they should not be forgotten forever. Teams should review and complete them.
Avoid Commented-Out Code
Commented-out old code makes files messy and confusing.
In professional projects, old code should usually be removed because version control systems can track previous versions.
Avoid This
// oldTotal = price + tax
// finalTotal = oldTotal - discount
// display(oldTotal)
Better Practice
finalTotal = calculateFinalTotal(price, tax, discount)
Keep the current code clean and remove unused old code.
Keep Comments Updated
Comments can become dangerous if they do not match the current code.
An outdated comment may mislead developers more than no comment at all.
Outdated Comment Example
// Apply 5% tax.
taxAmount = subtotal * 18 / 100
The comment says 5%, but the code applies 18%. This is confusing and dangerous.
Updated Comment
// Apply current tax rate to subtotal.
taxAmount = subtotal * taxRate / 100
The updated version is more accurate and flexible.
Write Comments in Clear Language
Comments should be easy to understand.
Avoid unclear abbreviations, personal jokes, emotional notes, or vague statements.
| Poor Comment | Better Comment |
|---|---|
// Magic fix |
// Handles missing address when user skips optional profile step. |
// Don't touch this |
// This order is required because payment validation depends on cart validation. |
// Stuff happens here |
// Generate monthly attendance summary for selected class. |
Student-Friendly Example: Grade Calculator Documentation
/*
Program: Grade Calculator
Purpose:
Accepts student marks and displays the grade.
Rules:
- Marks must be between 0 and 100.
- 90 and above: A
- 75 to 89: B
- 60 to 74: C
- 40 to 59: D
- Below 40: Fail
*/
INPUT marks
IF marks < 0 OR marks > 100 THEN
DISPLAY "Invalid marks"
ELSE IF marks >= 90 THEN
DISPLAY "Grade A"
ELSE IF marks >= 75 THEN
DISPLAY "Grade B"
ELSE IF marks >= 60 THEN
DISPLAY "Grade C"
ELSE IF marks >= 40 THEN
DISPLAY "Grade D"
ELSE
DISPLAY "Fail"
END IF
This documentation helps students understand the program rules before reading the logic.
Real-World Example: E-Commerce Checkout Documentation
/*
Module: Checkout Calculation
Purpose:
Calculates final payable amount for an order.
Business Rules:
- Discount is applied before tax.
- Delivery charge is added after tax.
- Free delivery applies when amount after tax is above 1000.
- Final amount must never be negative.
*/
FUNCTION calculateCheckoutAmount(subtotal, discountAmount, taxRate)
discountedAmount = subtotal - discountAmount
IF discountedAmount < 0 THEN
discountedAmount = 0
END IF
taxAmount = discountedAmount * taxRate / 100
amountAfterTax = discountedAmount + taxAmount
IF amountAfterTax > 1000 THEN
deliveryCharge = 0
ELSE
deliveryCharge = 50
END IF
RETURN amountAfterTax + deliveryCharge
END FUNCTION
The documentation explains the business rules that guide the calculation.
Best Practices for Comments
Recommended Comment Practices
- Write comments only when they add useful information.
- Explain why something is done, not just what is done.
- Keep comments short and clear.
- Update comments when code changes.
- Avoid comments that repeat obvious code.
- Avoid misleading or outdated comments.
- Do not leave large blocks of commented-out old code.
- Use TODO comments carefully and review them regularly.
- Use warning comments when changing code may cause risk.
- Prefer clean, expressive code over excessive comments.
Best Practices for Documentation
Recommended Documentation Practices
- Write a clear project README.
- Document public functions, APIs, modules, and important classes.
- Explain setup and run instructions clearly.
- Include examples where useful.
- Document assumptions, limitations, and dependencies.
- Keep documentation updated with code changes.
- Use consistent formatting and structure.
- Write documentation for the target audience.
- Avoid unnecessary long documentation for simple logic.
- Include troubleshooting notes for common errors.
Common Beginner Mistakes
Mistakes
- Commenting every single line.
- Writing comments that repeat the code.
- Not updating comments after changing code.
- Leaving old code commented out.
- Writing vague comments like “fix later” without detail.
- Using comments instead of improving poor variable or function names.
- Skipping README or setup instructions.
- Writing documentation only after the project is finished.
Better Habits
- Write clean code first.
- Comment only non-obvious logic.
- Explain decisions and business rules.
- Keep comments accurate and updated.
- Remove dead code instead of commenting it out.
- Write short README files for projects.
- Document reusable functions and APIs.
- Review documentation during code review.
Prerequisites Before Learning Comments and Documentation
Students should understand the following topics before learning this concept deeply:
Required Knowledge
- Basic programming syntax.
- Variables and data types.
- Functions or methods.
- Control flow and loops.
- Code readability.
- Naming conventions.
- Basic debugging concepts.
- Basic project structure.
Trace Table Example: Improving Comments
Let us see how a poor comment can be improved step by step.
| Step | Action | Result |
|---|---|---|
| 1 | Original code uses unclear variable names. | Reader cannot understand purpose quickly. |
| 2 | Rename variables clearly. | Code becomes self-explanatory. |
| 3 | Remove obvious comments. | Code becomes cleaner. |
| 4 | Add one useful comment explaining business rule. | Reader understands why calculation order matters. |
Practice Activity: Improve Comments
Improve the following pseudocode by removing unnecessary comments and adding one useful comment.
// Set subtotal
subtotal = 1000
// Set discount
discount = 100
// Subtract discount
amount = subtotal - discount
// Set tax
tax = amount * 5 / 100
// Add tax
finalAmount = amount + tax
DISPLAY finalAmount
Sample Improved Version
subtotal = 1000
discountAmount = 100
// Discount is applied before tax according to billing rules.
amountAfterDiscount = subtotal - discountAmount
taxAmount = amountAfterDiscount * 5 / 100
finalAmount = amountAfterDiscount + taxAmount
DISPLAY finalAmount
The improved version uses meaningful names and one useful comment.
Mini Quiz
What are comments in programming?
Comments are human-readable notes written inside source code to explain useful context, logic, or decisions.
Do comments affect program execution?
No. Comments are ignored by the compiler or interpreter and are written for human readers.
What should good comments explain?
Good comments should usually explain why something is done, especially when the reason is not obvious from the code.
What is documentation?
Documentation is written information that explains how software works, how to use it, how to maintain it, or how it is designed.
Why should comments be updated?
Comments should be updated because outdated comments can mislead developers and create confusion.
Interview Questions on Comments and Documentation
What is the difference between comments and documentation?
Comments are notes inside source code that explain specific logic or decisions, while documentation may explain the whole project, APIs, setup, architecture, or usage.
Why should developers avoid unnecessary comments?
Unnecessary comments create noise and may repeat what the code already clearly explains.
What is a good use of a TODO comment?
A TODO comment is useful for marking a specific pending task that should be completed or reviewed later.
Why is README documentation important?
README documentation helps developers understand the project purpose, setup steps, usage, folder structure, and common instructions.
What is self-documenting code?
Self-documenting code is code that is clear enough through naming, structure, and simplicity that it needs fewer explanatory comments.
Quick Summary
| Concept | Meaning |
|---|---|
| Comments | Human-readable notes written inside code. |
| Documentation | Written explanation of project usage, structure, APIs, setup, or design. |
| Good Comment | Explains useful context, decision, business rule, or warning. |
| Bad Comment | Repeats obvious code, becomes outdated, or misleads readers. |
| Docstring / Docblock | Structured documentation for functions, classes, modules, or APIs. |
| README | Project-level documentation that explains purpose, setup, and usage. |
| TODO Comment | Marks future work that should be reviewed or completed. |
| Self-Documenting Code | Code that is clear through naming, structure, and simple logic. |
Final Takeaway
Comments and documentation help developers understand software more easily, but they should be used wisely. Good code should first be clear through meaningful names, simple structure, and readable logic. Comments should explain useful context, especially why a decision was made or what business rule is being applied. Documentation should help others use, run, test, maintain, and extend the project. Professional developers write comments and documentation that are clear, accurate, updated, and helpful.