Salesforce rolled out a new feature in Winter 21 release, it’s called – SAFE NAVIGATION.
Safe navigation operator is a very useful syntax for Salesforce Developers and it will make the coding clean. The main purpose of this syntax is to avoid null pointer exceptions.
Basic Syntax
String accountName = accountRecord?.Name;
The above statement will store accountRecord.Name value in the variable accountName. As you can understand that accountRecord is basically the sObject variable holding Account record and then we are using that variable to fetch the Name property. Now, what will happen if the accountRecord is null, then null.Name will definitely give the null pointer exception, right? But the answer is No. Because we have used the safe navigation operator(?.) here. Safe navigation operator will make the check and if the accountRecord is not null, then only store the Name field to accountName, otherwise, it will just store null there.
How it works:
If the left side of the chain expression (?.) evaluates to null, then the right side will not be evaluated. This safe navigation can be used in the method, variable, and property chaining. The part of the expression that is not evaluated can include variable and property chaining.
Example 1:
Let’s say we have a method that will take the AccountNumber as a parameter and print the AccountName.
Before Winter 21 without Safe Navigation, our code will look like –
As you can see, in both the above codes, I am using either null check or isEmpty check. So basically I need to write some additional checks in the code. And here comes the advantage of Safe Navigation. Below code is with Safe Navigation –
Now in the above code, I have used the Safe Navigation operator which makes the code much cleaner, and most importantly I do not need to write explicit code for the null check. Isn’t it awesome?
Example 2:
Let’s say we have another method that will take the AccountNumber as a parameter and print the Account Description. But it will print the Account Description all in capital letters.
Without Safe Navigation we need to do something like –
In the above code, as you can see we are making couple of null checks – First whether the list is empty or not and second whether the Description field is null or not. If both the null check satisfies, then only we are applying toUpperCase() method to the description value. Definitely couple of lines of code and for sure Safe Navigation can help us here.
Here comes the same logic implemented with Safe Navigation –
Here I have used the Safe Navigation operator twice on the right side. Basically what I am trying, first making sure there is an account record and if yes trying to get the Description field and if the Description is not null, then only applying the toUpperCase() to the Description.
I have created a small video explaining this cool feature.