Learn something new every day
More Info... by email
Defensive programming is the creation of code for computer software designed to avoid problematic issues before they arise and make the product more stable. The basic idea behind this approach is to create a program that is able to run properly even through unforeseen processes or when unexpected entries are made by users. Defensive programming often relies on a somewhat paradoxical combination of eliminating unnecessary code while ensuring sufficient amounts are generated to handle all possible user actions. Extensive testing is also important for this process, as is the creation of software that can be audited and checked easily.
In many ways, the concept of defensive programming is much like that of defensive driving, in that problems are considered before they arise. One common method for attempting to do this is through the creation of code that is meant to deal with any possible scenario thrown at it. Programmers typically try to determine ways in which users are likely to enter input or try to use software that may be outside of expected parameters. The use of defensive programming is built upon the foundation of the code itself, which is designed to be able to handle strange input without crashing or encountering an error event.
Seemingly in contrast with this element of defensive programming, however, well written code needs to be devoid of unnecessary entries. The more lines of code that are part of a program, the more opportunities there are for errors to be introduced. Defensive programming practices typically encourage developers to eliminate unnecessary code and streamline programs whenever possible. A balance must be struck, therefore, between programming that accounts for unexpected scenarios and code that contains too much unnecessary content without providing a benefit.
Testing is one of the most important aspects of defensive programming. Despite a great deal of effort put into ensuring code is perfect, developers almost always miss a mistake or create code with unexpected results. Thorough testing by professional testers allows a developer to have hundreds of hours of product use to find errors before software is released.
The code itself that is created in defensive programming is also a vital aspect of this process. Not only should it be streamlined as much as possible, but it should also be presented in a way that is clear and concise. 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 this to be a realistic part of development.