1.7.3 Ensuring against Data Errors: Defensive Programming

Functions receive and output data. In primes, what happens if n is negative or so large that it exceeds the storage capacity allocated to the data structure implementing candidates? Think how upset a company's personnel would be if no one received paychecks because the input data for one employee was not valid. Or suppose each employee received an output check equal to the entire payroll. Defensive programming is ensuring that your programs guard against such outcomes by checking for invalid data, incoming or outgoing, and doing something reasonable when such data are discovered. What is reasonable can vary from signaling an error and stopping further processing to simply outputting an error message, ignoring the invalid data, and continuing processing. Sometimes the correct data may be inferred from the invalid data, but this approach must be taken with great caution. The important point is to ensure that errors are discovered. It is safer to have no output than output that is in error but thought to be correct. Invalid data is a very serious problem, regardless of whether it is due to design or to happenstance. Validation functions for input and output should be used, even though it is not always easy to see how to guard against all possible errors. This text does not have space to dwell on the issue of data validation, but it should always be in your mind.