Salesforce Safe Navigation Operator

SFDC Coder
2 min readAug 26, 2020

--

Next Article: LWC Barcode Scanner

Hello Guys,

Salesforce is rolling out a lot of new features in Winter 21 release. Out of them, there is one feature that is creating a lot of buzz now a days and that is Safe Navigation Operator.

What is this Safe Navigation Operator all about ??? How we can leverage it?

Safe Navigation Operator is very useful for Salesforce Developers and it will make their lives easy. By using this operator we can avoid null pointer exceptions.

Basic Syntax:

String accountNumber= accountRecord?.AccountNumber;

The above line of code returns account number of the given account record, but as we can see there is no null check on accountRecord before accessing AccountNumber field. Wouldn’t this statement create exception if accountRecord is null? And the answer is Noooopeee !!!! It wouldn’t fail and that’s the beauty of Safe Navigation Operator (‘ ?. ‘).

How: If the left-hand-side of the chain expression evaluates to null, the right-hand-side is not evaluated. We can use the safe navigation operator (?.) in method, variable, and property chaining. The part of the expression that is not evaluated can include variable and property chaining.

Let's go through a couple of more examples:

Example 1:

public Deal__c getLatestDealRecord(){// some logicreturn dealRecord;}Integer dealAmount = accountRecord?.getLatestDealRecord()?.Amount__c // It evaluates to null if accountRecord = null or getLatestDealRecord() method returns null.

Note that we are not bothered about the null check if we use this operator.

Example 2:

Before Winter 21

// Previous code checking for nulls
results = [SELECT Name FROM Account WHERE Id = :accId];
if (results.size() == 0) { // Account was deleted
return null;
}
return results[0].Name;

After Winter 21

// New code using the safe navigation operator
return [SELECT Name FROM Account WHERE Id = :accId]?.Name;

Please share your views on this cool feature. Looking forward to knowing how much excited you are feeling :)

Next Article: Salesforce Barcode Scanner

--

--

SFDC Coder

Salesforce Developer / Badminton Lover / Tech Enthusiastic