Skip to content
Questions
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 preconditionsBenefit
Error preventionBlocks invalid states/data before execution
DocumentationMakes function assumptions explicit to other developers
EfficiencyAvoids unnecessary defensive checks deeper in code
Worked Example
Worked Example: Stack Pop with Preconditions
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
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.