avoiding “attempt to de-reference a null object”

TL;DR

When working with related records anywhere in Salesforce always make sure the related record value is not null before attempting to use fields within that related record.  Also, when using a related record’s Id field, always use recordId instead of record.Id, or if it is a custom field use record__c instead of record__r.Id.

Why?

Let’s set the stage first.  null is a programming terminology that refers to the pointer or reference to something that does not exist.  In the context of Salesforce when you are writing logic in the context of a record, then that record can have relationships to other records via lookup and/or master/detail fields.  Let’s take an example of two objects named Account and ContactContact has a master/detail field to Account named ‘Account‘.

When you run a SOQL query “SELECT AccountId, Account.Id FROM Contact LIMIT 1”, assuming a record was returned and that record has a value set for the Account, then both AccountId and Account.Id will give you the same value.  If they are the same value, then what is the problem?  The problem starts with how you think about the fields.

  • AccountId is an Id field.
  • Account.Id is an object which contains an Id field called Id.

The problem here is when the related field, or Account in this example is not set to any value.  When this happens the value returned will be null, meaning it has no [valid] value.  So if Account is not a valid value, then Account.Id will cause a NullPointerException to be thrown since you can not obtain the Id field from a null value.  Since null is not a valid object, then trying to find anything from null will give you exceptions.

Summary

A best practice is to always check and ensure the relationship exists first before referencing any fields inside it, or if you are only needing the Id field from the relationship then use the Id field reference directly and not the record’s pointer to the Id field.