Comments That Explain a Decision

A useful comment records a domain rule or a reason a reader could not recover by following the control flow alone.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Preserve the original constraint
  2. Pass a change test
  3. Write down the rule that would be lost
  4. Keep a test close to the rationale

Preserve the original constraint

A maximum retry delay of 28 seconds may look arbitrary. A useful comment can explain that the surrounding request has a 30-second deadline and requires two seconds to report a failure. Readers can derive that the code clamps a value by reading the expression. The relation to the enclosing budget belongs with the function contract or the decision itself.

Pass a change test

Suppose a service raises its deadline to 45 seconds. A comment with the old numbers becomes a maintenance liability if the source never reads those settings. Where possible, derive the maximum from named values and comment on why time is reserved. Names with units keep the arithmetic understandable when the settings change.[1][2]

Write down the rule that would be lost

A weekly report excludes the current day. Without context, someone might see the missing row and “fix” the loop to include it. A comment can record that the current day has incomplete observations and that the report compares seven completed days. A name like last_completed_day helps make that intent visible in the code. The comment can then concentrate on why partial days are excluded and where the day boundary comes from. See conditions on dates and times for the role of the chosen time zone.

For another example, suppose a sort retains the input order when two inspection scores tie. The comment can explain that equal scores must remain in submission order so reviewers see the earlier observation first. That decision is more useful than a comment repeating which standard sort function is called.

Keep a test close to the rationale

A comment establishes a reason. A test can preserve the relevant behavior when someone changes the implementation. For the weekly report, use data on both sides of midnight and one entry on the partially collected day. A boundary test can check which rows appear, while an explanation can document why the boundary was chosen.

Review the comment when the policy changes. If the report later supports an option to include a partial day, spell out which mode the statement applies to. Replace references to arbitrary line numbers with a stable concept or requirement where possible. The goal is that a maintainer reading the function can recover the important decision without reconstructing its history from scratch.

References

  1. Python Software Foundation, Python Language Reference: Execution Model ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩