Sunday 20 December 2020

Safe Navigation Operator

Hi,

Here we learn how can we use Safe Navigation Operator:

We Use the safe navigation operator (?.) to replace explicit, sequential checks for null references.

This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.

If the left-hand-side of the chain expression evaluates to null, the right-hand-side is not evaluated. 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.

This example first evaluates a, and returns null if a is null. Otherwise, the return value is a.b.

a?.b // Evaluates to: a == null ? null : a.b

This example indicates that the type of the expression is the same whether the safe navigation operator is used in the expression or not.

Integer x = anObject?.anIntegerField; // The expression is of type Integer because the field is of type Integer

This example shows a single statement replacing a block of code that checks for nulls.

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

This example shows a single-row SOQL query using the safe navigation operator.

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



References:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SafeNavigationOperator.htm

https://trailhead.salesforce.com/en/content/learn/modules/platform-developer-i-certification-maintenance-winter-21/get-handson-with-field-and-objectlevel-security-and-safe-navigation-operator


No comments:

Post a Comment

How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...