Inputs, and Data
Defensive coding produces code that accepts the fact that, inputs are going to be invalid, other code is probably not going to work right, and the data is bad. In other words real world coding. Sometimes as programmers we get caught in our own little bubbles where data is perfect, and nothing ever returns a null, but that is a pipe dream. In the real world things change, and people make mistakes, and coding defensively is way to deal with this fact.
To code defensively you must understand the following:
- Don’t make assumptions
- You can’t control user input.
- You can’t trust the data.
- You can’t trust other code.
- The requirements will change.
- It always takes longer than you thought.
- You can do it right now, or do it right again later.
Defensively coding is necessary when confidence levels in technical, or other aspects of software project are low. Defensive coding is not a solution, but a compensenatory technique for producing high quality code when coditions do not foster it. Some people might say that defensive coding smells, and it’s not ideal, but I believe it to be acceptable when rewriting a project, or reworking other aspects of the project are not a viable option.
Examples of defensive coding using VB.NET
Example 1. Null check from a database call.
Dim myDbObject as DbObject
Dim myValue as string
myDbObject = DbLayer.GetDbObject()
If myDbObject IsNot Nothing then
myValue = myDbObject.Property
End If
Example 2. Checking input data
Public Sub GetInput(ByVal Input as DateTime)
If Input > DateTime.MinValue AndAlso Input <>
DbLayer.SaveDate(Input)
Else
DbLayer.SaveDate(DateTime.MinValue)
End If
End Sub
In example one, the basic premise is that we define our variable rather than just using the object value straight from the database, and check if it’s null before using it. This is basic common sense, but this pattern can be extrapolated out, and inplementing these checks will never serve you wrong. In the second example before passing data back to the database we check to see if the date values are within range. This is a basic check, but it is likely to cause errors when dealing with date inputs. It is always a good idea to use a basic check to see if your data is at least in a general range. It will save you headaches later.
These were very rudimentary examples, but this is the fundamental of coding defensively. This all can be distilled down to the idea that you can only control data once it is inside of your application, and everthing else will probably be corrupt, invalid, or buggy at some point, so deal with it.
To be continued













One Comment
There's a lot of value to what you're saying. Coding using the assumption that everything that gets thrown at your software is going to be complete crap will save you a ton of headaches later on. As someone who has done pretty extensive database programming, I can attest to that. Nice writing! Keep up the good work!