3 min read

Guarding Against Null Reference Errors in Apex Code

The joy of debugging and troubleshooting a null-reference error is enough to make you want to toss your notebook (or whatever is handy) through a wall (maybe I have anger issues...haha).

So I wanted to write a few tips that have helped me reduce the number of times I come across this error and saved my sanity.

Tip 1: Find a good defensive programming balance

The most obvious way of preventing a null reference error would be to check that an instance of an object is not null. This would fall under defensive programming where you are guarding against invalid data. It works but it can make your code very inefficient, highly verbose, and most of all it's a false sense of security.

Instead, look for ways to control the instantiation of your classes where possible. Maybe by only exposing constructors that require required data to be past in as part of the object instantiation. You could also use static methods on an object whose only purpose is to generate a valid instance and not expose a constructor at all.

The goal is to find balance by implementing safe guards where you can control instantiation to make sure you are minimizing risk and minimizing the number of is null statements you would need to make in your code.

Tip 2: Know your data types

Many of us are not just Salesforce or Apex developers. We come from a background in programming that ranges from VB, Java, C#, and even C and what that means is we have a lot to remember in terms of variable instantiation and what the language takes care of for us. For instance, nullable types are something you have to explicitly define in a language like C# for certain data types, which means we tend to not worry about checking for nulls on things like numbers or booleans.

However, in Apex just about every native data type is nullable. Which means we have to explicitly check that these data types are not null before attempting to access instance methods. If we are just displaying input and output, nulls are not really an issue but if we wanted to perform calculations or evaluate the value of certain items then we would need to make sure a valid value is present.

One particular error that has happened more than once is assuming a boolean of null will evaluate to false. If you choose to use the short hand if structure of "if (x)" and x is null you will get a null reference error. If you did this in Visual Studio using C# the compiler would recognize that you are using a variable that has not been initialized or in run-time warn that you are attempting to set a boolean to a null value.

You can easily test this scenario in Apex by opening Eclipse and on the execute anonymous tab run the following code:

boolean x;
if (x) System.Debug('Success');

You will receive the following error message:

Error Occured

You can solve for this by explicitly testing for true or false:

boolean x;
If (x == true) System.Debug('Success');

Just beware that if x is null (x == false) will return false and (x == true) will return false.

Tip 3: Make use of constructors to initialize your properties

I have seen some creative uses of class constructors from time to time but my preference is not to place any logic in a constructor and primarily reserve that block to initialize my property values. This allows me to avoid null reference errors by explicitly defining what the default value of my properties should be. It also simplifies construction and reserves any initialization logic to an initialization method or static method that instantiates the object.

Below is an example of a class that has a static method for instantiation:

public class Sandbox {
    
    //Property
    public boolean IsActive {get;set:]
    
    //Constructor
    private Sandbox() {
        IsActive = true;
    }
    
    //Static Method
    public static Sandbox getInstance() {
        Sandbox oSandbox = new Sandbox();
        return oSandbox;
    }
}

In the example above I use a static method to create an instance and I make the constructor private so that the only way to create an instance is with the static method. This doesn't work for all situations but it illustrates a way to control the instantiation of objects for instances where it is warranted.


So that is all the tips I have for now. If you have any tips or tricks that you use to help improve the reliability of you code, please post a comment.