Use of Safe Navigation Operator
Instead of using explicit, sequential checks for null references, use the safe navigation operator (?.). This new operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.
NOTE: All Apex types are implicitly nullable and can hold a null value returned from the operator.
Example -
Account acc = [SELECT Name FROM Account WHERE Id = :accId];if (acc != null) {
return acc.Name;
}
Using Safe Navigation Operator
String accName = acc?.acc.Name;
String accName = [SELECT Name FROM Account WHERE Id = :accId]?.Name;
The Safe Navigation Operator (?.) in Apex is a feature that allows developers to safely navigate objects and data structures, avoiding null pointer exceptions. When you use the Safe Navigation Operator to access a chain of references, Apex will evaluate the expression from left to right and return null immediately if it encounters a null reference rather than throwing a null pointer exception.
Typically, you use nested if statements or ternary operators to check for nulls before dereferencing an object, but the Safe Navigation Operator simplifies this process.
Here's an example of how the Safe Navigation Operator can be used:
Without the Safe Navigation Operator
Account a = [SELECT Id, Name, Primary_Contact__r.Name FROM Account WHERE ...];
if (a != null && a.Primary_Contact__r != null) { String primaryContactName = a.Primary_Contact__r.Name; }
With the Safe Navigation Operator
Account a = [SELECT Id, Name, Primary_Contact__r.Name FROM Account WHERE ...];
String primaryContactName = a?.Primary_Contact__r?.Name;
In the second example, if a or a.Primary_Contact__r is null, primaryContactName will be assigned null instead of throwing a NullPointerException. This operator significantly reduces the boilerplate code required to perform null checks, making your Apex code cleaner and more readable. Remember that although the Safe Navigation Operator helps avoid NullPointerException (NPEs), it's important to properly handle cases where the value is null as per the business logic necessities.
Resources
Comments
Post a Comment