Defensive Readability
intermediate12 min readLesson 116 of 180
Guard clauses, early returns, and structure over cleverness โ code that prevents misreading.
Defensive readability
Write code that prevents misreading:
- guard clauses first โ fail fast, then the happy path reads straight down without else-nesting:
if (order == null) throw new IllegalArgumentException("order required");
if (order.items().isEmpty()) return OrderResult.empty();
// happy path continues at indentation 0
- early returns over else-terraces โ each
elseadds a level the reader must track - expressions over statements where the name is the point:
boolean isAdult = age >= 18;beats re-readingage >= 18four times - structure beats cleverness โ the branchless bit-trick version of
maxcosts a comment and a future bug;Math.maxcosts nothing
The test: could a teammate skimming a PR diff misread any line? If yes, rename, extract, or flatten until the answer is no.