While I was reading the book Code Complete: A Practical Handbook of Software Construction, Second Edition, I learned what defensive programming is and more specifically, how many actions programmers can choose to take when dealing with unexpected or bad inputs.
What Is Defensive Programming?
According to the Code Complete book,
In defensive programming, the main idea is that if a routine is passed bad data, it won’t be hurt, even if the bad data is another routine’s fault. More generally, it’s the recognition that programs will have problems and modifications, and that a smart programmer will develop code accordingly. - Code Complete, Chapter 8: Defensive Programming
I, thus understand the concept of defensive programming as 'Correctively dealing with unexpected(which mostly means 'bad') data so that letting the program still functional as expected.' Let me know if you find or think there is something wrong with this way of understanding..
There are many ways of defensive programming discussed in the book. One of the ways of defensive programming is called assertion.
The code below is the example of the assertions discussed in Java from this book:
This assertion checks if denominator is 0; if it's 0, then it should be highlighted and the programmer need to know that, so it will display a message saying
denominator is unexpectedly equal to 0.
Defensive Programming for Having Safety Net and Program Efficiently
The example above was just one of the many examples of ways of defensive programming in the book. Defensive programming allows programmers to have a simple, but useful safety net from crashing the program or unexpected errors or bugs that may cause the development slow, which definitely will be crucial and serious if you are doing that for living, certainly. Thus, defensive programming is an option that all programmers have, to protect themselves and program efficiently.