Skip to main content

Code Readability Basics: Worked Examples

Work through each trace before reading the explanation. Then solve the transfer task without the page open.

Example 1: Zero can hide missing data​

An average function returns zero for empty input. A caller can no longer distinguish no measurements from measurements whose mean is zero.

Choose and document a contract: rejection, optional result, or a justified domain default. An optional mean keeps missing data separate. For [0,0], [2,4], and [], expect 0,3,and missing respectively. Renaming the function does not restore lost information.

Example 2: Similar code can express separate policies​

Tax and shipping calculations both multiply by a rate. Combining them into one configurable business-policy class may tie together rules that change independently.

Extract arithmetic only if units and rounding contracts match. Keep domain decisions separate. Test the proposed abstraction with a change request: tax rounding changes tomorrow while shipping behavior must remain identical. Good cleanup reduces the cost of this change rather than merely eliminating repeated characters.

Transfer and self-check​

Should a timeout and an empty search result both return an empty list? Check: no matches and unknown results are different outcomes that callers may handle differently.

Evidence to keep​

Save your first attempt, corrected reasoning, and transfer result as checkpoint evidence. A matching final answer without an explanation is insufficient. Continue with the guided lab and use the reading guide to repair a specific gap.