Syllabus Lesson 71 of 141 · APIs nobody can misuse
APIs nobody can misuse

Small is safe

Why it matters After three problems that needed states, enums and value types, it is tempting to wrap everything in a class. A plain function with named arguments and two checks can already be impossible to misuse.

Every service in the company retries failed calls with exponential backoff, each with its own hand-written loop. You are writing the one shared helper that says how long to wait before attempt n. It is called from dozens of places, so it must be hard to call wrongly, and it must be easy to read.

Your turn

Write retry_delay(attempt, *, base_ms, cap_ms): return min(cap_ms, base_ms * 2 ** (attempt - 1)). Hidden misuse scripts will try these. TypeError: passing base_ms or cap_ms by position, or leaving either out. ValueError: an attempt below 1, a base_ms of 0 or less, or a cap_ms below base_ms (usually the two swapped). Rule: your whole code may have at most 70 syntax nodes (code_size).

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.