Precondition and Postcondition

◀ Function▶ One Function Versus Multiple Functions
Amazon A function’s precondition refers to what must hold before the function is executed, and a function’s postcondition refers to what will be true or changed after the execution of the function in addition to what it returns.

If the function modifies a global variable, for example, this variable’s state should be included in the preconditions. A tremendous number of bugs occur due to incomplete understanding of preconditions and postconditions of a function.

For instance, if you pass a negative integer to a function that handles only positive integers, you get weird results or even a segmentation fault.

Another example is that if the result of calling a function is further processed by the program, you need to make sure the program can deal with every single possible result the function returns. That is why if you do not pay enough attention to a function’s preconditions and postconditions, it is highly possible that your function works on some arguments and crashes on others.

Let me give you an actual coding example. Consider the following function:
int get_sum(int first_int, int second_int, int &sum){
sum = first_int + second_int; return sum; }
This function computes the sum of the two given integers and stores it in the given argument sum as well as returning it. In this case the precondition is that first_int and second_int are valid integers bound by C++’s integer maximum value and minimum value. And the postcondition is that the sum of those integers is returned and variable sum is updated to store the value of the sum.

Knowing exactly the state of the program before and after the execution of a function is extremely important. It will greatly reduce logic errors and confusion.

From my experience, many bugs that occur in a program are due to imprecise or incomplete understanding of preconditions and postconditions of one or more functions used in the program. We will discuss how important they are in Chapter 12.
◀ Function▶ One Function Versus Multiple Functions

Questions? Let me know!