Defensive programming

Under defensive programming, a programming of computer systems is understood to be checked as many conditions even before the actual end in itself is met. A programmer is faced with various known and unknown aspects regarding user input, different operating systems and versions. The so defensive programmed applications are suspicious of all inputs and assumptions and behave robust against violations. By anticipating as many circumstances they continue to run or break off in an orderly process.

An alternative approach to defensive programming is design by contract. This is the component that takes the service of another component in claim solely on the basis of a contract, a number of preconditions safe and relying on postconditions that have been defined for the service provided in the contract. In defensive programming, however, the preconditions were unclear, while the postconditions should be reviewed by the relevant in every component.

A system must not prescribe a single approach to. Basically, it can be divided so that external events ( user input, data import, API) are defensively to handle, while that is not required for internal operations.

Examples

  • A printer entry should be deleted. The program defensively created first checks whether the printer is to be addressed at all present. The program checks the return value of the delete function. If can not be deleted due to missing access rights, the program attempts to grant the rights and try deleting again.
  • A file should be copied from one directory to another directory. A defensive program checks whether the source directory exists and is readable. Then it is checked whether the target directory is present and writable. It does not exist, the program creates the required directory itself and gives itself, if necessary, before the required rights. Finally, the file is then copied to the existing verified and accessible directories.
  • The input of a user runs completely contrary to expectations ( see figure). A programmer with vision recognizes such possible situations and checks the user input before the actual processing starts. In the example of the figure, the program would have to cancel the process and the user display a message that it must correct the entries.

Opposite of defensive programming

The programmer - depending on the language - various other means of exception handling, exception handling. These possibilities are, however, no longer subsumed under the term defensive programming, but it's about to catch any occurring, unpredictable errors. Just contrary to the defensive programming, for example, the popular Visual Basic statement On Error Resume Next behavior ( colloquially also called OERNy from an unknown source, in German " just continue "). The advantage is that the application does not crash, though with a incalculable consequences, that is, the result may be completely incorrect in certain circumstances.

225422
de