Defensive programming is writing code for computer software designed to prevent problematic issues before they arise and to make the product more stable. The basic idea behind this approach is to create a program that is able to function properly even in unforeseen processes or when unexpected input is made by users. Defensive programming often relies on a somewhat paradoxical combination of eliminating unnecessary code, ensuring that sufficient amounts are generated to handle all possible user actions. Extensive testing is also important to this process, as is creating software that can be easily audited and verified.
Software testing is one of the most important aspects of defensive programming.
In many ways, the concept of defensive programming is very similar to defensive driving, in that problems are considered before they arise. A common method of trying to do this is by creating code intended to handle any possible scenario thrown at it. Programmers typically try to determine the ways in which users are likely to enter data or attempt to use software that may be outside of expected parameters. Defensive programming usage is built on the foundation of the code itself, which is designed to be able to handle extraneous input without crashing or encountering an error event.
Defensive programming can be used to eliminate unnecessary code.
Seemingly in contrast to this defensive programming element, however, well-written code needs to be devoid of unnecessary inputs. The more lines of code that are part of a program, the more opportunities there are for bugs to be introduced. Defensive programming practices typically encourage developers to eliminate unnecessary code and optimize programs whenever possible. A balance must be struck, therefore, between programming that takes into account unexpected scenarios and code that contains a lot of unnecessary content without providing a benefit.
Testing is one of the most important aspects of defensive programming. Despite a great effort to ensure that the code is perfect, developers almost always miss an error or create code with unexpected results. Thorough testing by professional testers allows a developer hundreds of hours of product usage to find bugs before the software is released.
The very code that is created in defensive programming is also a vital aspect of this process. Not only should it be simplified as much as possible, but it should also be presented in a clear and concise manner. Audits are often used by a developer to review code that has been created. This allows other programmers to see the work that has been done, and readable code is important for it to be a realistic part of development.