Safe Navigation Operator ?.

Tired of writing repeated null check statements?? if then here is your new favorite operator(?.) coming from Salesforce as part of Winter 21 release.

We might have come across several instance where we need to write some sequential checks for null references in our code to overcome “NullPointerException” mostly related to data issues with in our org or as required by business.

What the new operator does? If 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 references, method references, or array expressions.

Let’s see how we can make use of this new feature in practice.

Assume you have to evaluate an SOQL statement in apex and return response accordingly.

// 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;

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

When it comes to an object or variable it can be used as follows:

// Previous code checking for nulls
String profileUrl = null;
if (user.getProfileUrl() != null) {
	profileUrl = user.getProfileUrl().toExternalForm();
	}

// New code using the safe navigation operator
String profileUrl = user.getProfileUrl()?.toExternalForm();

Reference:

https://releasenotes.docs.salesforce.com/en-us/winter21/release-notes/rn_apex_SafeNavigationOperator.htm

Leave a Reply

%d bloggers like this: