02 November 2017

what is defensive programming

When writing code usually we will cover ALL positive cases covered because that is what testers will test for. And also depending upon the clarity in requirements you will also code for negative test cases like non admin users should not have access to settlement reports or order reports, etc.

But we need to improve our coding skills beyond just meeting the stated functionality in terms of security, invalid inputs, unexpected errors etc.

Defensive programming example # 1

For example if some application is sending you the XML as input and says, XML they send is always going to valid as per the XSD document, then it’s better to check whether given XML is per the shared XSD or not when input is received. If not we should throw an error back to application saying the input XML doesn’t match the XSD definitions.

If you assume input is always be valid, then your application is prone for unexpected error like null reference exceptions or "object reference not set to an instance of an object", etc. Such unexpected errors are time consuming to DEBUG and fix them. So it’s always better to think what can go wrong and write the code to handle such scenarios.

Defensive programming example # 2

Let's assume you are going to build a web application to view business critical reports. Probably you show a link to a user from the business heads group to view the list of such reports in a page. When a user click on a report to your app will displays the report in detail. While your app, rendering such detail report, you need to again validate whether the user is having the enough privilege to view the report. If not, you should throw HTTP 403 Forbidden error.

While displaying the detailed report, if you don't check for the required privilege then your business critical information is easily accessible to any other application user as long as they have a valid URL to view such a report.

As a defensive programming practitioner you will add a explicit check before you start processing the request to show the detailed report.


This kind of programming which anticipates what can go wrong and writes the logic to handle that errors gracefully is called defensive programming. You need to become defensive programming practitioner to avoid unexpected errors and security breaches.

No comments:

Post a Comment