Replacing Repeated Choices with a Lookup

For a fixed key and one result per key, a data table can express a decision compactly.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Make the table explicit
  2. Give unknown codes a policy
  3. Work with a small table whose keys are unambiguous
  4. Decide which decisions still need logic

Make the table explicit

For label codes A, B, and C mapping to red, green, and blue, use a mapping of code to label. Lookup separates the list of cases from the procedure that retrieves the label. Hashable collection keys support direct lookup in a dictionary.

Give unknown codes a policy

An unrecognized D could produce an error or a documented fallback. A None value used legitimately for a hidden label makes a missing-key sentinel useful. See sentinel values for keeping explicit absence separate from a stored null value.[1][2]

Work with a small table whose keys are unambiguous

A display can map exact status codes to colors. A dictionary might give active the color green and paused amber. Looking up a valid key chooses its value without executing a separate branch for every known status. That makes the mapping easy to review as data. A status with no color can be legitimate for a hidden entry, so use an explicit absent-key outcome if the table can also store null. See dictionary lookups.

Decide which decisions still need logic

A table is suitable when the same key always selects the same output under its contract. If the outcome also depends on a date or another condition, you could use a documented compound key when the domain is finite. Otherwise a predicate can express the rule more directly. For example, color may depend on active status and whether today is past a deadline.

Test a known typical key, a known key with an intentionally empty value, and an unrecognized key. If the table is built from configuration, detect repeats before deciding whether they replace an earlier entry. Stable comparison keys helps avoid collapsing distinct inputs.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩