Definition
Preconditions are specific conditions that must be met before a program or function can execute successfully. They ensure inputs are valid and the program operates without errors.
Purpose of Preconditions
Key Point
| Purpose of preconditions | Benefit |
|---|---|
| Error prevention | Blocks invalid states/data before execution |
| Documentation | Makes function assumptions explicit to other developers |
| Efficiency | Avoids unnecessary defensive checks deeper in code |
Worked Example
Worked Example: Stack Pop with Preconditions
Without preconditions: The function might crash or return garbage data when popping from an empty stack.
With preconditions: The function handles the error gracefully, returning a meaningful error message.
pseudocode
function pop(stack):
// PRECONDITION: Stack is not empty
if isEmpty(stack) then
return ERROR("Cannot pop from empty stack")
end if
item = stack[top]
top = top - 1
return item
end function
With preconditions: The function handles the error gracefully, returning a meaningful error message.