intermediate language-deep-dive

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.

Part of: How Clean works

require enforces the rules a function needs to work correctly:

start:
	print(divide(10.0, 4.0).toString())
	print(repeat("ab", 3))

functions:
	number divide(number a, number b)
		require b != 0.0
		return a / b

	string repeat(string text, integer times)
		require times > 0
		require text.length() > 0
		string result = ""
		iterate i in 0 to times - 1
			result = result + text
		return result
2.5
ababab

require 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:

start:
	print(grade(95))
	print(grade(73))
	print(grade(55))

functions:
	string grade(integer score)
		require score >= 0
		require score <= 100
		if score >= 90
			return "A"
		if score >= 80
			return "B"
		if score >= 70
			return "C"
		if score >= 60
			return "D"
		return "F"
A
C
F

Anyone 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.

  • 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
📚 → Book 1, Chapter 7 : Error Handling in Depth →
Copied!