There is one particular issue that seems to be the root of most bugs in software programs. I see it over and over and over. Like most programmers, it has caused me heartburn since the day I started programming. So I have worked hard to make sure that my code never breaks my golden rule. I remind my development team every chance I get to also follow what I call the golden rule of programming. I think every new programmer needs a tatoo that says it.
So what is the golden rule of programming?
“If it can be null, it will be null”
Null reference type errors are responsible for a good percentage of all application bugs. They are usually very simple problems. Typically caused by not adding additional logic to ensure that objects have valid values before using them.
How about some simple examples of null values causing problems?
Here is a classic example below. A string variable passed in to a method is used before ensuring it isn’t null. KA-BOOM!
public void DoSomething(string text)
if (text.ToUpper() == "Hello World")
Some of the most common causes are settings, database calls, or API type calls not returning expected values. For example, you add a new field to your database and don’t populate default values for every record. Randomly records get queried and the code didn’t account for that new field being null. KA-BOOM!
The good news is that a lot of null reference errors can be avoided by adding additional logic and code to ensure objects are not null before trying to use them. Developers should always assume that everything is FUBAR and be very defensive in their code. Pretend every database call is going to fail, every field is going to have messed up data in it.
Some tips to prevent null reference exceptions:
- Initialize variables with valid values.
- If a variable can be null, then check for null and handle it appropriately
- For C# use the ?? operator with strings when appropriate. ex. (stringvar ?? “”).ToUpper()
If you follow my golden rule, I promise you will have far fewer bugs in your apps. Because if it can be null, it will be null!