Defensive Programming

Learn about the defensive programming approach to software design.

Defensive programming follows a somewhat different approach to DbC. Instead of stating all conditions that must be held in a contract, which, if unmet, will raise an exception and make the program fail, this is more about making all parts of the code (objects, functions, or methods) able to protect themselves against invalid inputs.

Defensive programming is a technique that has several aspects, and it is particularly useful if it is combined with other design principles (this means that even though it follows a different philosophy from DbC, that doesn't mean that it is a case of using one or the other—they could complement one another).

The main ideas for defensive programming are how to handle errors for scenarios that we might expect to occur, and how to deal with errors that should never occur (when impossible conditions happen). The former will fall into error handling procedures, while the latter will be the case for assertions.

Error handling

In our programs, we resort to error handling procedures for situations that we anticipate will be prone to causing errors. This is usually the case for data input. The idea behind error handling is to gracefully respond to these expected errors in an attempt to either continue our program execution or decide to fail if the error turns out to be insurmountable.

Get hands-on with 1400+ tech skills courses.