Contracts with require
A require statement is a precondition — a rule that must be true when a function is called. Instead of burying defensive checks deep in the function body, require states the contract at the top where every reader sees it immediately.
require enforces the rules a function needs to work correctly:
functions:\n number divide(number a, number b)\n require b != 0.0\n return a / b\n\n string repeat(string text, integer times)\n require times > 0\n require text.length() > 0\n string result = ""\n iterate i in 0 to times - 1\n result = result + text\n return result\n\nstart:\n print(divide(10.0, 4.0).toString())\n print(repeat("ab", 3))2.5\nabababrequire b != 0.0 states that divide requires b to be non-zero. If someone calls divide with 0.0, an error is signaled before the division — no cryptic runtime crash. Multiple require statements are allowed and checked in order.
require makes the valid input range immediately visible:
functions:\n string grade(integer score)\n require score >= 0\n require score <= 100\n if score >= 90\n return "A"\n if score >= 80\n return "B"\n if score >= 70\n return "C"\n if score >= 60\n return "D"\n return "F"\n\nstart:\n print(grade(95))\n print(grade(73))\n print(grade(55))A\nC\nFAnyone reading grade sees immediately: this function works with scores 0 to 100. The require statements are the function's contract — they document the expected inputs and enforce them. Code that passes invalid values fails at the require line, not somewhere inside the logic.
Quick recap
- require condition signals an error if the condition is false
- Place require statements at the very top of the function, before any logic
- Multiple require lines are allowed — each is checked in order
- require is documentation AND enforcement — the contract is visible to every reader