Defensive Coding
What is defensive coding?
No matter how good we are at programming, we could still commit some errors in our code. Even the most experienced and skilled developers make mistakes that result in errors. Some errors are easy to find - like typing errors. The VWD IDE shows such errors and we can easily correct them. Others are more complicated and difficult to find.
The first step to write an error-free program is to code defensively. What it means is that we should try to anticipate everything that could go wrong in our application and then write code to prevent it. To do this, we must learn to think like the user of our application.
Here is a very simple example: Let us say we have a page with a text box for entering a number. Our application calculates the square of that number and displays the result. When we test our application, we know what is needed to enter. Therefore, we enter a valid number and the application works fine.
However, not every user will have our mindset. Even if we provide a clear instruction on the page that a number is required, some users may not follow it. There may be some mistake in typing or wrong text was entered intentionally. In such a case, our application will fail because it is not coded to handle such invalid inputs.
The correct way is to write the code so that it will first check the value entered in the text box. If that value is a valid number, only then the square calculation code will execute. Otherwise, an error message should be shown to the user.
This was a simple example but it demonstrates that we should not make any assumptions, especially about the user inputs. In the last chapter, we have learned about classes and methods (function). Some methods need arguments (parameters) to work. We should always check that correct arguments are passed to the methods. Otherwise, they would produce an incorrect result or may not work at all.