Code Snippets Do's and Don'ts — Writing Effective Code Examples
In this tutorial, you will learn about Code Snippets Do's and Don'ts. We cover key concepts, practical examples, and best practices to help you master this topic.
Code snippets are the most used element of developer documentation. Well-written snippets teach concepts quickly. Poorly-written snippets waste time and destroy trust. This lesson covers the specific do's and don'ts of writing code snippets.
In this lesson, you will learn what makes a code snippet effective and what mistakes to avoid.
What You'll Learn
You will write complete, runnable code snippets, avoid common snippet mistakes, and format snippets for maximum readability.
Why It Matters
Developers copy and paste code snippets. Every snippet should work correctly the first time.
Real-World Use
DodaTech reviews every code snippet as part of the documentation review Process. Snippets are tested automatically to ensure they produce the documented output.
flowchart LR
A[Code Snippet] --> B{Complete?}
B -->|Yes| C{Tested?}
B -->|No| D[Add Imports]
C -->|Yes| E{Publishes}
C -->|No| F[Test Output]
A:::current
classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px
The Do's
Do include all imports and setup. The snippet must compile and run when copied.
Do show expected output. Use comments to show what the reader should see.
Do include error handling for real-world examples. Developers need to handle failures.
Do use meaningful variable names. Avoid foo, bar, baz.
Do show one concept per snippet. Keep it focused.
# DO: Complete, runnable with expected output
from pathlib import Path
from dodazip import Compressor
def backup_logs(log_dir: str, output_dir: str) -> list[dict]:
"""Compress all .log files in a directory."""
compressor = Compressor(algorithm="gzip", level=6)
results = []
for log_file in Path(log_dir).glob("*.log"):
result = compressor.compress_file(
input_path=str(log_file),
output_path=str(Path(output_dir) / f"{log_file.name}.gz"),
)
results.append({
"file": log_file.name,
"original": result.input_size,
"compressed": result.output_size,
})
return results
results = backup_logs("/var/log/myapp", "/backups/logs")
print(f"Compressed {len(results)} files")
# Expected: Compressed 5 files
The Don'ts
Do not skip imports. A snippet that defines compress_file but never imports it is useless.
Do not use placeholder names. foo, bar, thing, data tell the reader nothing.
Do not assume prior setup. If the reader needs a specific library version, say so.
Do not show only the happy path. Include error handling.
Do not use deprecated patterns. Check that your snippet uses current API.
# DON'T: Incomplete, no imports, placeholder names
def do_thing(data):
result = compressor.compress(data)
return result
# DON'T: No imports, undefined compressor, not runnable
# DON'T: foo and bar as variable names
# DON'T: Missing expected output
Common Mistakes
1. Missing Imports
def compress_file... but no import statement. Readers must guess what to import.
2. Undefined Variables
Using compressor without creating it. Readers must figure out the missing step.
3. No Output
Showing code but not what it produces. Readers cannot verify their results.
4. Fake Placeholders
Using foo, bar, x, data. Readers cannot understand what the code does.
5. No Context
A snippet without explanation of what it demonstrates. Readers do not know what to learn.
6. Too Much Code
One snippet trying to demonstrate three different features. Break into multiple snippets.
7. Deprecated API
Using old function names or parameters. Readers learn outdated patterns.
Practice Questions
1. What makes a code snippet runnable?
All imports and variable definitions included. The snippet works when copied and pasted.
2. Why should you show expected output?
Developers need to verify their results. Expected output confirms they are on the right track.
3. What is wrong with foo and bar as variable names?
They convey no meaning. Readers cannot understand what the code does or how to adapt it.
4. Why include error handling in snippets?
Real-world code needs error handling. Snippets teach patterns developers should use.
5. Challenge: Take a code snippet from documentation that violates three or more don'ts. Rewrite it following all the do's.
FAQ
Mini Project
Audit three code snippets from documentation you use. Evaluate each against the do's and don'ts. Rewrite any snippets that violate three or more rules.
What's Next
Next: Sample Code Projects
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro