Defensive programming

Defensive programming is the practice of creating or designing code in a way that will avoid issues before they can affect the system. The idea behind it is that developers will not be able to predict every sort of permutation of input or error that can affect the system they are designing. To combat this, programmers write their code in a way that will prevent or mitigate vulnerabilities that can be caused when unforeseen issues arise. A commonly seen example of defensive programming occurs when user input is required to query a database. SQL injections are a type of cyberattack that uses a vulnerability in the way the system process queries. It works when queries are not coded properly, and users are able to ‘inject’ SQL commands using the available input (Imperva, 2021). A common way this can happen is when user input is not formatted a certain way, i.e. made into a string before processing. Defensive programming in this instance would include ensuring all inputs are turned into strings or integers before querying. Additionally, ensuring that all invalid commands, or input that do not meet the correct criteria for querying, output a message instead of simply allowing them to go through the system is a good defense.

Defensive programming should definitely be a part of the architecture of any software or system. A common practice of defensive programming is ensuring that any unnecessary code is removed. Not only does this make a program require less resources to run, it reduces the chance of attackers using vulnerable code by removing it entirely if it is unnecessary. In that way, defensive programming allows for more efficient processes while also protecting systems from attack.



Imperva. (2021, March 11). What is SQL injection: SQLI attack Example & Prevention Methods: Imperva. Learning Center. Retrieved December 30, 2021, from,lists%20or%20private%20customer%20details.

Wiesen, G. (2021, February 20). What is defensive programming? EasyTechJunkie. Retrieved December 30, 2021, from

Sample Solution