Naming Variables with Units and Meaning

Names carry information about units, expected state, and domain meaning that the underlying numeric or text value cannot express alone.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Keep units visible
  2. Preserve meaning at an API boundary
  3. Put a conversion next to the unit change
  4. Make the meaning of a count visible too

Keep units visible

The number 3000 could represent milliseconds, seconds, or bytes. A name such as timeout_ms lets the reader check it before passing it to a call expecting seconds. Test the conversion with a value far from zero. Three thousand milliseconds should become three seconds. Bind intermediate results at the point where the unit changes.

Preserve meaning at an API boundary

A counter called size is ambiguous in an upload routine. byte_count distinguishes encoded length from the number of characters. An input of é has length one in Python as a string and encodes to two bytes in UTF-8. A function contract can put that distinction in the parameter description so every caller uses the same unit.[1][2]

Put a conversion next to the unit change

An upload interface can receive elapsed milliseconds and pass seconds to a timer API. Consider an input of 2500 milliseconds. Storing delay_s = delay_ms / 1000 gives 2.5 seconds. Passing delay_ms directly would request 2500 seconds. When the receiving parameter is named only delay, the two calls can look equally plausible. Give conversion results their own names and carry the accepted unit into the function contract.

Use a nonround input to test the distinction. A delay of zero would pass many incorrect conversions. A delay of 2500 can reveal division by the wrong factor or an integer conversion that loses half a second. If an external interface accepts only whole seconds, decide whether the requested duration rounds up, rounds to nearest, or is rejected. Rounding boundaries explain why the desired engineering rule matters.

Make the meaning of a count visible too

Imagine a job processing twelve input rows. Nine are accepted, two invalid, and one unread after a failure. An unqualified count cannot tell the caller which population it describes. Separate rows_read, rows_accepted, and an expected total when the job reports those facts. Nine and eleven are both legitimate observations about the same run. The distinction becomes important when dividing accepted rows by the number examined.

Check one report where a row has valid structure but is excluded by a filter. Does its presence increase rows read, rows accepted, both, or neither? Write a small example that makes these answers visibly different. The same care with names helps when documenting rates alongside counts.

References

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