Questions: Function Design and Contracts

5 questions to test your understanding

Score: 0 / 5
Question 1 Multiple Choice

A function calculate_average(numbers) divides the sum by the length of the list. A colleague calls it with an empty list, causing a division-by-zero crash. Whose responsibility is this failure under a contract-based design approach?

AThe function's — it should handle any input it might receive, including empty lists, to be robust
BThe caller's — the precondition 'list must contain at least one element' was violated
CBoth equally — the function should have defensive code and the caller should have checked
DNeither — this is a language runtime bug, not a design problem
Question 2 Multiple Choice

A developer finds that her function is hard to write a contract for — the postconditions have many special cases and the preconditions are tangled and interconnected. What does this signal?

AThe function needs more thorough documentation to cover all the edge cases in the contract
BThe function handles a genuinely complex problem and a complicated contract is expected
CThe function is doing too much and should be decomposed into smaller functions, each with a clean contract
DThe contract concept does not scale well to complex functions and should be abandoned here
Question 3 True / False

A well-designed function should be able to handle any input it receives, even invalid ones, by returning a sensible default or raising a graceful error.

TTrue
FFalse
Question 4 True / False

Writing a function's contract before implementing it — specifying preconditions and postconditions first — helps clarify what the function should do and guides how to test it systematically.

TTrue
FFalse
Question 5 Short Answer

How does thinking in terms of preconditions and postconditions change the approach to testing a function, compared to testing without a formal contract?

Think about your answer, then reveal below.