Defensive programming is the practice of anticipating problems that may arise in a software system and writing code to keep the system in a good state when such problems occur. A common way to apply defensive programming (also called defensive coding) is by verifying inputs to individual functions or methods. The guard clause pattern is a common way to perform validation of inputs while also minimizing complexity in the function.
Defensive programming is when a programmer anticipates problems and writes code to deal with them.
Defensive programming's techniques
Check all data from external sources: when obtaining data from files, networks, or external sources, check the value of the data obtained to ensure that it is within the date range. Example: When we request user's age, It should be a positive number, and maybe not larger then 150?
Check the parameters values for the methods: Example: Train Arrival time should be a Datetime type, not null or random integer numbers.
Decide how to deal with incorrect data: discovering an incorrect parameter, how do you deal with it? Depending on the situation, you can choose the mode that suits you, either by asserting or maybe throwing exceptions?
Real life scenarios?
1- If you are developing an API as a software engineer, you should check for all the values provided through the REST verbs in the controller side.
2- More coding examples:
Conclusion
The beauty of this defensive programming technique is that it costs almost no time to add exhaustive type checking to your code. Also it is a build up technique, It makes your application more solid against different types of invalid inputs.
Top comments (0)