Safe Navigation Operator In Salesforce

Introduction

Safe Navigation Operator is introduced by Salesforce to prevent the NULL POINTER EXCEPTION.
Null Pointer Exception basically occurs when there is no value or null is assigned to the variable. It’s the most common exception we usually see in our code.
E.g. Account accObj; //null reference creation
System.debug(accObj.Name); // returns Null Pointer Exception
Safe Navigation Operator is represented by ‘?.’.

It returns us the null instead of throwing a Null pointer exception in our code. We can use it in methods, variables, and properties.
E.g. System.debug(accObj?.Name); //returns null

Safe Navigation Operator Example In Salesforce

# firstVar ?. secVar

In this example, if firstVar evaluates to true, it will return firstVar.secVar value and if it evaluates to false, we get null.

# without Safe Navigation Operator

Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, LastName FROM Contact]);

// null check

if(conMap.get(‘ 0035g00000bDUhoBAK’) != null){

System.debug(conMap.get(0035g00000bDUhoBAK’).LastName);

}

In w/o safe navigation operator, we are doing a null check explicitly using if statement. Means if mentioned is Id present in the org, then we get the LastName of that particular Id’s record.

#with Safe Navigation Operator

Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, LastName FROM Contact]);

System.debug(conMap.get(0035g00000bDUhoBAK’)?.LastName);

In with safe navigation operator, we can see

conMap.get(0035g00000bDUhoBAK’)?.LastName

In the above statement, if the record’s Id is present (condition is true), then it will give that record’s last name and if not present, it will give us a null instead of null pointer exception.

There are certain specific cases in which we aren’t allowed to use Safe Navigation Operator. We will get errors if we try to use operator in those cases which include assignable expressions.

e.g. count?.c = 2;

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.