Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software under unforeseen circumstances. Defensive programming practices are often used where high availability, safety or security is needed.
Defensive programming is an approach to improve software and source code, in terms of:
Overly defensive programming however introduces unnecessary code for errors impossible to even happen, thus wasting runtime and maintenance costs. There is also the risk that the code traps or prevents too many exceptions, potentially resulting in unnoticed, incorrect results.
Secure programming is the subset of defensive programming concerned with computer security. That is to say, security is the concern, not necessarily safety or availability (the software may be allowed to fail in certain ways). As with all kinds of defensive programming, avoiding bugs is a primary objective, however the motivation is not as much to reduce the likelihood of failure in normal operation (as if safety was the concern), but to reduce the attack surface – the programmer must assume that the software might be misused actively to reveal bugs, and that bugs could be exploited maliciously.
The function will crash when the input is over 1000 characters. Some novice programmers may not feel that this is a problem, supposing that no user will enter such a long input. This particular bug demonstrates a vulnerability which enables buffer overflow exploits. Here is a solution to this example:
Offensive programming can be considered a category of defensive programming, with the added emphasis that certain errors should not be handled defensively. In this practice, only errors from outside the program's control are to be handled (such as user input); the software itself, as well as data from within the program's line of defense, are to be trusted in this methodology.
Here are some defensive programming techniques:
If existing code is tested and known to work, reusing it may reduce the chance of bugs being introduced.
However, reusing code is not always a good practice, because it also amplifies the damages of a potential attack on the initial code. Reuse in this case may cause serious business process bugs.