Stackify is now BMC. Read theBlog

The Golden Rule of Programming

By: mwatson
  |  August 17, 2023

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")
     {
          //do something
     }
}

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:

  1. Initialize variables with valid values.
  2. If a variable can be null, then check for null and handle it appropriately
  3. 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!

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]