6 exercises — practise the WHY not WHAT rule, choosing the right marker (TODO/FIXME/HACK), and writing comments that give future developers the context they need.
0 / 26 completed
1 / 26
You have this line of code:
`results = results.filter(x => x.status !== "deleted")`
Which comment follows the "WHY not WHAT" rule?
Option B explains WHY: "soft-deleted records are retained in the DB for audit; exclude from all API responses". This gives context that the code alone cannot convey — the business rule (audit retention), the architectural decision (soft delete), and the scope (all API responses).
The "WHY not WHAT" rule: • The code already tells you WHAT it does — you can read it • A useful comment tells you WHY — the intent, constraint, or reason that isn't obvious
Bad comment: // filter out deleted records — just restates the code Good comment: // soft-deleted items kept in DB for SOC2 audit trail; excluded from public API
When to write an inline comment: • Non-obvious algorithm or logic • Business rule that comes from requirements, not code • Workaround for an external bug or constraint • Magic number ("0.8" → "// 80% capacity threshold from SLA contract") • Warning about a subtle side effect ("// mutates the input array")
2 / 26
A colleague asks you to add a comment to this code:
`const MAX_RETRIES = 3;`
Which comment adds the most value?
Option C explains WHY the value is 3, not 1, 2, or 10. This is the best comment because it documents: 1. The empirical observation (vendor drops ~2% of requests) 2. The business reasoning (>99.9% success rate) 3. The source of the value ("empirically") — this came from testing, not guessing
This is the type of information that would otherwise live only in the head of the developer who wrote it, or in a Jira ticket no-one would find again.
Magic number commenting pattern: • const TIMEOUT_MS = 30000; // 30s — Firebase cold start latency; set empirically in load test • const BATCH_SIZE = 100; // DynamoDB write limit per batch request • const MIN_PASSWORD_LENGTH = 12; // NIST SP 800-63B recommendation
The value "3" in option C is a magic number only when seen without context. With the comment, it becomes a documented engineering decision.
3 / 26
You need to leave a comment about a known bug that you cannot fix right now because it requires a significant refactor. Which marker and wording is most appropriate?
Option B uses the conventional FIXME marker and provides all the information the next developer needs:
1. FIXME: — conventional marker for known bugs (visible in TODO/FIXME linters) 2. race condition — names the specific type of bug 3. when multiple requests arrive in the same millisecond — describes the triggering condition 4. needs mutex or atomic compare-and-swap — suggests two concrete solutions 5. see issue #4112 — links to the tracking issue for full context
FIXME best practices: • Be specific: describe what is broken and when it happens • Suggest a solution if you have one • Link to an issue/ticket if one exists • Optionally add your initials and date: // FIXME(alex, 2024-03): ...
Format: // FIXME: [what is wrong] — [when it happens] — [suggested fix or issue link]
4 / 26
When should you NOT write a comment?
When the comment restates the code — "noise comments" reduce readability without adding value.
Examples of noise (do NOT write these): • i++ // increment i • return null; // return null • user.save(); // save the user • // constructor above a constructor function • // getter for name above a getName() function
When to write comments (do write these): • Algorithm or logic that is non-obvious ✓ • External constraint or known bug workaround ✓ • Business rule not visible in the code ✓ • Warning about side effects or mutation ✓ • Explaining a deliberate performance trade-off ✓ • Citing a source for a magic number or formula ✓
The standard: if a competent developer in your team would understand the code without the comment, omit it. If the comment would prevent future confusion or incorrect changes, include it.
5 / 26
You need to leave a note about a security-sensitive section. Which comment is most effective?
Option C uses a SECURITY marker and explains the specific risk, the correct approach, and WHY the common alternative is dangerous — all in one actionable comment.
Security comments should be explicit about consequences: • // SECURITY: validate all user input before this point reaches the query builder • // SECURITY: do NOT log this value — it contains PII (GDPR Art.4) • // SECURITY: tokens expire in 15 min — do NOT extend; see auth spec §3.2 • // SECURITY: constant-time comparison required (see OWASP timing attack)
The constant-time comparison note in option C is a real, important pattern: normal string comparison (===) short-circuits as soon as it finds the first mismatch, so an attacker can measure response times to guess characters in a secret one by one. A constant-time function always takes the same time regardless of where the mismatch occurs, preventing the side channel.
6 / 26
You are writing a comment to explain a temporary workaround. Choose the best phrasing.
Option B is the best temporary workaround comment. It provides: 1. HACK: marker — signals temporary code to anyone reading or searching 2. What the workaround is — polling instead of webhooks 3. WHY it is necessary — Stripe sandbox limitation 4. Source — documentation link for verification 5. Removal condition — "remove when upgrading to live mode"
The removal condition is especially valuable: it transforms a vague hack into a task with a clear trigger. A future developer switching to live mode will search the codebase and find this exact note.
HACK / workaround comment format: // HACK: [what the workaround does] — [why it's needed] — [link to source/issue] — [when to remove]
Without clear workaround documentation, temporary code becomes permanent code — the developer who understands the context leaves, and no-one dares remove it.
7 / 26
During a code review for a new payment processing service, your team lead points out this section:
// Calculate total amount due.
let total = items.reduce((acc, item) => acc + item.price * item.quantity, 0);
He asks you to provide a comment for this code snippet. Which of the following options best demonstrates providing context without simply stating the obvious?
The key to effective inline comments is focusing on *why* the code does what it does, not just *what* it does. Option A is insufficient because it merely points out a potential error without context. While option B is okay, it doesn't explain the reasoning behind the calculation. Options C and D both provide valuable context, linking the calculation to its business purpose – this demonstrates understanding and facilitates future maintenance or changes.
8 / 26
During a code review of a new user authentication service, you encounter this section:
const isValidUser = await bcrypt.compare(password, user.hashedPassword);
Your reviewer asks you to add a comment explaining why you're using `bcrypt.compare` instead of just comparing the password directly. Which of the following comments best addresses this request while adhering to good commenting practices?
// Compare password with hashed password for security
The incorrect options simply restate what the code does or offer a general security disclaimer without explaining *why* `bcrypt.compare` is crucial. Option 1 is too verbose and describes the action rather than the reason. Option 2 correctly identifies the core benefit – secure password handling – but doesn't explain the technical process behind it. Option 3 is tempting, but stating something is 'insecure' without context isn't helpful; the correct answer focuses on the *reason* for using a secure hashing function like bcrypt.
9 / 26
During a code review of a new API endpoint that retrieves user profiles, your team lead asks you to comment on this section:
const userData = await api.getUserProfile(userId);
Which comment would best demonstrate providing context and rationale for the asynchronous call without simply stating what it does? Consider the potential implications of a failed API request.
The correct answer (option 1) provides context by explaining *why* the `await` keyword is used – to handle potential network errors. It also clarifies the function being called (`api.getUserProfile`) and its purpose. Options A & B are overly simplistic; option C simply restates the obvious, while D focuses on post-processing rather than the initial API call itself. Good comments explain *why* code is written a certain way, not just *what* it does.
10 / 26
You're reviewing a PR for a new user registration service. The following code snippet handles validation:
const username = req.body.username;
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
return res.status(400).send('Invalid username format');
}
Your team lead asks you to add a comment to this code. Which of the following options best demonstrates providing context and rationale for the regular expression without simply stating what it does? Consider potential edge cases or future modifications.
The correct answer (option 2) provides a *why* - it explains the purpose of the validation step. Options A and C simply describe what the regex does, neglecting to explain *why* this specific format is being enforced or the potential for future changes. Option D focuses on security but doesn't provide context around the validation process itself. Good comments should always explain the 'why' behind a decision, not just the 'what'.
11 / 26
During a code review for a new payment processing service, your team lead points out this section:
// Calculate total amount due.
let total = items.reduce((acc, item) => acc + item.price * item.quantity, 0);
He asks you to provide a comment for this code snippet. Which of the following options best demonstrates providing context without simply stating the obvious?
The key to effective inline comments is focusing on *why* the code does what it does, not just *what* it does. Option A is insufficient because it merely points out a potential error without context. While option B is okay, it doesn't explain the reasoning behind the calculation. Options C and D both provide valuable context, linking the calculation to its business purpose – this demonstrates understanding and facilitates future maintenance or changes.
12 / 26
During a code review of a new user authentication service, you encounter this section:
const isValidUser = await bcrypt.compare(password, user.hashedPassword);
Your reviewer asks you to add a comment explaining why you're using `bcrypt.compare` instead of just comparing the password directly. Which of the following comments best addresses this request while adhering to good commenting practices?
// Compare password with hashed password for security
The incorrect options simply restate what the code does or offer a general security disclaimer without explaining *why* `bcrypt.compare` is crucial. Option 1 is too verbose and describes the action rather than the reason. Option 2 correctly identifies the core benefit – secure password handling – but doesn't explain the technical process behind it. Option 3 is tempting, but stating something is 'insecure' without context isn't helpful; the correct answer focuses on the *reason* for using a secure hashing function like bcrypt.
13 / 26
During a code review of a new API endpoint that retrieves user profiles, your team lead asks you to comment on this section:
const userData = await api.getUserProfile(userId);
Which comment would best demonstrate providing context and rationale for the asynchronous call without simply stating what it does? Consider the potential implications of a failed API request.
The correct answer (option 1) provides context by explaining *why* the `await` keyword is used – to handle potential network errors. It also clarifies the function being called (`api.getUserProfile`) and its purpose. Options A & B are overly simplistic; option C simply restates the obvious, while D focuses on post-processing rather than the initial API call itself. Good comments explain *why* code is written a certain way, not just *what* it does.
14 / 26
You're reviewing a PR for a new user registration service. The following code snippet handles validation:
const username = req.body.username;
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
return res.status(400).send('Invalid username format');
}
Your team lead asks you to add a comment to this code. Which of the following options best demonstrates providing context and rationale for the regular expression without simply stating what it does? Consider potential edge cases or future modifications.
The correct answer (option 2) provides a *why* - it explains the purpose of the validation step. Options A and C simply describe what the regex does, neglecting to explain *why* this specific format is being enforced or the potential for future changes. Option D focuses on security but doesn't provide context around the validation process itself. Good comments should always explain the 'why' behind a decision, not just the 'what'.
15 / 26
During a code review for a new payment processing service, your team lead points out this section:
// Calculate total amount due.
let total = items.reduce((acc, item) => acc + item.price * item.quantity, 0);
He asks you to provide a comment for this code snippet. Which of the following options best demonstrates providing context without simply stating the obvious?
The key to effective inline comments is focusing on *why* the code does what it does, not just *what* it does. Option A is insufficient because it merely points out a potential error without context. While option B is okay, it doesn't explain the reasoning behind the calculation. Options C and D both provide valuable context, linking the calculation to its business purpose – this demonstrates understanding and facilitates future maintenance or changes.
16 / 26
During a code review of a new user authentication service, you encounter this section:
const isValidUser = await bcrypt.compare(password, user.hashedPassword);
Your reviewer asks you to add a comment explaining why you're using `bcrypt.compare` instead of just comparing the password directly. Which of the following comments best addresses this request while adhering to good commenting practices?
// Compare password with hashed password for security
The incorrect options simply restate what the code does or offer a general security disclaimer without explaining *why* `bcrypt.compare` is crucial. Option 1 is too verbose and describes the action rather than the reason. Option 2 correctly identifies the core benefit – secure password handling – but doesn't explain the technical process behind it. Option 3 is tempting, but stating something is 'insecure' without context isn't helpful; the correct answer focuses on the *reason* for using a secure hashing function like bcrypt.
17 / 26
During a code review of a new API endpoint that retrieves user profiles, your team lead asks you to comment on this section:
const userData = await api.getUserProfile(userId);
Which comment would best demonstrate providing context and rationale for the asynchronous call without simply stating what it does? Consider the potential implications of a failed API request.
The correct answer (option 1) provides context by explaining *why* the `await` keyword is used – to handle potential network errors. It also clarifies the function being called (`api.getUserProfile`) and its purpose. Options A & B are overly simplistic; option C simply restates the obvious, while D focuses on post-processing rather than the initial API call itself. Good comments explain *why* code is written a certain way, not just *what* it does.
18 / 26
You're reviewing a PR for a new user registration service. The following code snippet handles validation:
const username = req.body.username;
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
return res.status(400).send('Invalid username format');
}
Your team lead asks you to add a comment to this code. Which of the following options best demonstrates providing context and rationale for the regular expression without simply stating what it does? Consider potential edge cases or future modifications.
The correct answer (option 2) provides a *why* - it explains the purpose of the validation step. Options A and C simply describe what the regex does, neglecting to explain *why* this specific format is being enforced or the potential for future changes. Option D focuses on security but doesn't provide context around the validation process itself. Good comments should always explain the 'why' behind a decision, not just the 'what'.
19 / 26
During a code review for a new payment processing service, your team lead points out this section:
// Calculate total amount due.
let total = items.reduce((acc, item) => acc + item.price * item.quantity, 0);
He asks you to provide a comment for this code snippet. Which of the following options best demonstrates providing context without simply stating the obvious?
The key to effective inline comments is focusing on *why* the code does what it does, not just *what* it does. Option A is insufficient because it merely points out a potential error without context. While option B is okay, it doesn't explain the reasoning behind the calculation. Options C and D both provide valuable context, linking the calculation to its business purpose – this demonstrates understanding and facilitates future maintenance or changes.
20 / 26
During a code review of a new user authentication service, you encounter this section:
const isValidUser = await bcrypt.compare(password, user.hashedPassword);
Your reviewer asks you to add a comment explaining why you're using `bcrypt.compare` instead of just comparing the password directly. Which of the following comments best addresses this request while adhering to good commenting practices?
// Compare password with hashed password for security
The incorrect options simply restate what the code does or offer a general security disclaimer without explaining *why* `bcrypt.compare` is crucial. Option 1 is too verbose and describes the action rather than the reason. Option 2 correctly identifies the core benefit – secure password handling – but doesn't explain the technical process behind it. Option 3 is tempting, but stating something is 'insecure' without context isn't helpful; the correct answer focuses on the *reason* for using a secure hashing function like bcrypt.
21 / 26
During a code review of a new API endpoint that retrieves user profiles, your team lead asks you to comment on this section:
const userData = await api.getUserProfile(userId);
Which comment would best demonstrate providing context and rationale for the asynchronous call without simply stating what it does? Consider the potential implications of a failed API request.
The correct answer (option 1) provides context by explaining *why* the `await` keyword is used – to handle potential network errors. It also clarifies the function being called (`api.getUserProfile`) and its purpose. Options A & B are overly simplistic; option C simply restates the obvious, while D focuses on post-processing rather than the initial API call itself. Good comments explain *why* code is written a certain way, not just *what* it does.
22 / 26
You're reviewing a PR for a new user registration service. The following code snippet handles validation:
const username = req.body.username;
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
return res.status(400).send('Invalid username format');
}
Your team lead asks you to add a comment to this code. Which of the following options best demonstrates providing context and rationale for the regular expression without simply stating what it does? Consider potential edge cases or future modifications.
The correct answer (option 2) provides a *why* - it explains the purpose of the validation step. Options A and C simply describe what the regex does, neglecting to explain *why* this specific format is being enforced or the potential for future changes. Option D focuses on security but doesn't provide context around the validation process itself. Good comments should always explain the 'why' behind a decision, not just the 'what'.
23 / 26
During a code review of a new feature that calculates shipping costs, your team lead asks you to add a comment to this section:
const shippingCost = calculateShipping(package.weight, package.destination);
Which of the following comments best explains the purpose of this calculation?
A: "This line calculates the total price of the product." B: "This calculates the shipping cost based on the package weight and destination, ensuring accurate delivery fees are applied."
C: "This is a placeholder for future integration with a third-party shipping API." D: "This updates the user's account balance after each purchase."
The correct answer (B) focuses on *why* the calculation is happening – to determine shipping costs. Options A and D are too broad; option C describes a potential future change, not the current purpose. It's crucial to explain the *reasoning* behind code, not just what it does.
24 / 26
During a code review of a new microservice responsible for processing user orders, your senior developer asks you to explain the purpose of this comment:
// Retrieve product details from the database.
Which of the following options best describes how you should phrase your response in a code review message?
The correct answer highlights the importance of specificity in code comments. Many non-native speakers may assume that 'retrieving product details' is sufficient; however, good comments should clearly state *what* data is being retrieved and *why*. Option A reflects a passive acceptance of the comment without critical evaluation – the core issue is lack of detail.
25 / 26
You're drafting a Slack message to your team about a recent change you made to the payment processing module. The following code snippet was updated:
const totalAmount = items.reduce((acc, item) => acc + item.price * item.quantity, 0);
You want to add a comment that explains why this calculation is performed. Which of the following options would be most appropriate for your Slack message?
The best response acknowledges the need to explain *why* the code is calculating the total amount. Option 0 provides a clear and concise explanation suitable for Slack communication. The other options either offer insufficient detail or assume an unnecessary level of understanding from team members.
26 / 26
During a code review of a new feature that calculates shipping costs, your team lead asks you to add a comment to this section:
const shippingCost = calculateShipping(package.weight, package.destination);
Which of the following options best describes how you should write this comment?
The key here is providing context for the called function. A good comment should explain *what* parameters are being passed to `calculateShipping` and what that function *does*. This allows other developers to quickly understand the flow of execution and potential dependencies – a frequent challenge for non-native speakers.
What will I practice in "Writing Inline Comments — Code Comments Exercises"?
This is a Code Comments exercise set. It walks through 26 scenario-based multiple-choice questions built around real usage of Code Comments terminology that IT professionals encounter on the job.
Is this exercise free to use?
Yes. Every exercise on CoderSlingo, including this one, is free to complete with no account, sign-up, or paywall.
How many questions are in this exercise?
This set contains 26 questions. Each one shows immediate feedback and a detailed explanation after you answer, so you learn the correct usage right away rather than waiting for a final score.
Do I need prior experience to complete this exercise?
No prior experience is required. Each question includes a full explanation covering the reasoning behind the correct answer, so the exercise itself teaches the Code Comments vocabulary as you go.
Can I retry the exercise if I get questions wrong?
Yes — use the "Try again" button on the results screen to reset your answers and go through all the questions again. There is no limit on attempts.
Is my progress saved?
Your answers and score for the current session are tracked in the browser as you go. No account or login is needed, and there is nothing to install.
What if I don't understand a term used in a question?
Read the explanation shown after you answer each question — it breaks down the correct term in plain English with a real-world example. You can also check the site Glossary for quick definitions.
How is this different from reading a blog article on the topic?
Exercises like this one are interactive drills that test and reinforce specific vocabulary through multiple-choice questions, while blog articles explain concepts in prose. Practising here after reading builds active recall, not just passive recognition.
Where can I find more Code Comments exercises?
See the Code Comments exercises hub for the full set of related pages, or browse all exercise categories from the main Exercises index.
Can I use this exercise to prepare for a technical interview?
Yes — Code Comments vocabulary comes up often in technical discussions and interviews. Pair this exercise with our dedicated Interview Preparation section for role-specific practice.