To comment and document code well, explain why the code does what it does, not what each line says. Markers use your comments to judge whether you understand your own solution.
This guide shows what good comments contain, a before and after example, how to write docstrings and file headers, what goes in a README and the mistakes that cost marks. It ends with a submission checklist and how STEM Donkey can help.
The Three Layers of Well-Documented Code
Good documentation has three layers. Clear names make each line readable. Docstrings or header comments explain what each function or class does, its inputs, outputs and errors. Inline comments explain the reasons behind non-obvious decisions.
On top of that, a README tells someone how to build, run and test the project. If a marker can run your code and understand it without asking you anything, it is well documented.
What Good Comments Explain
The code already shows what happens. Comments add the information the code cannot carry on its own.
- Intent: the purpose of a block, such as "remove duplicates while keeping first-seen order".
- Reasons: why you chose one approach over an obvious alternative.
- Assumptions: conditions the code relies on, for example "input list is already sorted".
- Units and ranges: "timeout in seconds", "probability between 0 and 1".
- Known limits: cases the code does not handle, and why.
- References: the algorithm or source you followed, such as a textbook section.
Before and After: The Same Function Three Ways
Here is one small Python function documented badly, excessively and well.
Under-Documented
def f(a, t):
r = []
for x in a:
if x > t:
r.append(x)
return r
It works, but a reader has to decode every name to see the purpose.
Over-Commented
def f(a, t):
r = [] # make an empty list
for x in a: # loop over a
if x > t: # if x is bigger than t
r.append(x) # add x to r
return r # return r
Every comment repeats the code. It adds length without adding understanding.
Well Documented
def readings_above(readings, threshold):
"""Return the readings strictly greater than threshold.
Args:
readings: list of sensor values in degrees Celsius.
threshold: cut-off value in degrees Celsius.
Returns:
A new list, in the original order.
"""
return [r for r in readings if r > threshold]
Clear names remove the need for inline comments, and the docstring states the units, the strict inequality and the order of the result.
Naming Does Half the Work
The cheapest documentation is a good name. Rename before you comment.
| Unclear | Clear | Why it is better |
|---|---|---|
| d | elapsed_days | States the quantity and the unit |
| temp | temperature_c or swap_value | Removes the ambiguity of "temp" |
| flag | is_valid | A boolean reads as a yes or no question |
| process() | remove_outliers() | Says what the function actually does |
| list1, list2 | students, grades | Describes the contents |
Follow your language's conventions: snake_case for Python functions, camelCase for Java methods, PascalCase for classes in both.
Function and Class Documentation
Every public function, method and class should have a docstring or documentation comment. Use the format your course or language community expects.
- Python: a triple-quoted docstring as the first statement, often in Google or NumPy style. Tools such as help() read it.
- Java: a Javadoc comment starting with /** above the method, with @param, @return and @throws tags.
- C and C++: a block comment above the function, or Doxygen-style comments if your course uses Doxygen.
- JavaScript: JSDoc comments with @param and @returns.
Javadoc example.
/**
* Returns the arithmetic mean of the given scores.
*
* @param scores array of exam scores, each from 0 to 100
* @return the mean score
* @throws IllegalArgumentException if scores is empty
*/
public static double mean(int[] scores) {
if (scores.length == 0) {
throw new IllegalArgumentException("scores is empty");
}
long total = 0; // long avoids overflow on very large arrays
for (int s : scores) {
total += s;
}
return (double) total / scores.length;
}
The single inline comment explains a decision (using long), which a reader might otherwise question. The cast to double prevents integer division.
File Header Comments
Many courses ask for a header at the top of each source file. Keep it short and factual.
# File: inventory.py
# Purpose: Track stock levels and flag items below reorder point.
# Course: CS101, Assignment 3
# Usage: python inventory.py stock.csv
# Notes: Requires Python 3.10 or later.
Include your name or student number only if your course requires it. Avoid change logs in the header; version control records history better.
Writing a README
A README is the first file a marker opens. It should let them run your work in a few minutes.
| Section | What to write |
|---|---|
| Overview | One or two sentences on what the program does |
| Requirements | Language version and any libraries, with install commands |
| How to run | Exact commands and an example input |
| How to test | The command that runs the tests and what success looks like |
| Design notes | Main files, data structures and any assumptions |
| Known limitations | What does not work yet, stated honestly |
Documenting Tests
Tests are documentation too: they show exactly what the code is meant to do. Give each test a descriptive name and, where useful, a one-line comment on the case it covers.
def test_readings_above_excludes_equal_values():
# threshold itself is not "above", so 20.0 is dropped
assert readings_above([19.5, 20.0, 21.2], 20.0) == [21.2]
Comment Syntax by Language
| Language | Single line | Block or documentation |
|---|---|---|
| Python | # comment | """docstring""" |
| Java | // comment | /* block */ and /** Javadoc */ |
| C and C++ | // comment | /* block */ |
| JavaScript | // comment | /** JSDoc */ |
| R | # comment | #' roxygen2 comments |
| MATLAB | % comment | %{ block %} |
| SQL | -- comment | /* block */ |
Common Documentation Mistakes
- Restating the code: "increment i" above i += 1 tells the reader nothing.
- Out-of-date comments: a comment that contradicts the code is worse than none. Update comments when you change logic.
- Commented-out code left in: delete it before submission.
- No docstrings on public functions: markers often check these specifically.
- Jokes or frustration in comments: keep the tone professional.
- A README that does not run: test your own instructions on a clean copy of the project.
A steady habit helps more than a last-minute pass. Documenting each function as you write it is a lighter load than documenting forty at once at midnight.
What Markers Look for, and a Submission Checklist
Rubrics vary, but documentation marks usually reward the same few things. Knowing them lets you spend effort where it counts.
| Criterion | What earns the marks |
|---|---|
| Readability | Descriptive names, consistent style and sensible function length |
| API documentation | Docstrings that state inputs, outputs, units and errors |
| Explanation of design | Comments or a README section that justify key choices |
| Reproducibility | Run and test instructions that work first time |
| Honesty about limits | Known issues stated clearly rather than hidden |
Before you submit, work through this list.
- Every public function and class has a docstring with inputs, outputs and errors.
- Inline comments explain reasons, assumptions and units, not syntax.
- Names are descriptive and follow the language's conventions.
- Each file has the header your course requires.
- The README's run and test commands work on a clean copy.
- No commented-out code, debug prints or stale comments remain.
How STEM Donkey Helps with Code Documentation
Send the assignment specification, your language and version, and any style guide your course uses. A writer prepares custom, tested code with docstrings, focused inline comments, file headers and a README, or documents and tidies code you have already written.
Use it to see what well-documented code looks like, then apply the same habits to your own work. Free revisions within the scope of your original request are included.
Want Code That Explains Itself?
Send the specification and your language. You get custom, tested code with docstrings, focused comments and a README that tells a marker how to run it.
Order Your Programming AssignmentFree revisions · Full refund if late · Written from scratch for your order
Frequently Asked Questions
There is no fixed ratio. Every public function needs a docstring, and inline comments belong wherever a reader would ask "why?". Clear code with good names needs fewer comments.
A comment is ignored by the language and explains code to readers. A Python docstring is a string stored with the function, which tools such as help() and documentation generators can read.
No. Line-by-line comments usually repeat the code. Comment blocks of logic and non-obvious decisions instead.
No. Compilers and interpreters ignore comments, so they have no effect on running speed.
Use the one your course specifies. If none is given, Google style and NumPy style are both widely used. Pick one and use it consistently.
If the brief asks for one, yes. Even when it does not, a short README with run instructions makes marking easier.
Docstrings and block comments read best as full sentences. Short inline comments can be brief phrases.
Yes. Send your code and the brief. A writer can add docstrings, comments and a README, and point out unclear names.