Avoid null pointer exception with Safe Navigation Operator Apex

Telegram logo Join our Telegram Channel

Winter 2021 is out with a much-awaited feature for apex developers. With this, you can say goodbye to the clumsy null check statements. Yes, it is the Safe Navigation Operator (?.) M in Apex.

Safe Navigation Operator Apex


Note: If you are reading this article in the release preview period, it might not work in your org if the org is not in Winter 2021 release preview.

What does the Safe Navigation Operator do?

You can use this operator to avoid explicit, sequential null checks. This operator breaks the execution of the expression that attempts to operate on a null reference and returns null instead of throwing null pointer exception.

This operator works on all apex types. Cool, right?


Syntax of the Safe Navigation Operator

leftExpression ?. rightExpression

Example:

x ?. y


How Safe Navigation Operator works?

As we saw the syntax of this operator it has two operands, left and right, these operands can be individual objects or expressions. 

If the left-hand side of the expression results in null, then the right side of the expression is not executed.

The right side of the expression can be variable references, method references, or array references. 


Examples of Safe Navigation Operator in Apex

Let's see the classic example of the turnery operator. In the below example we are extracting the account name from the account reference.

Example 1:

String accountName = account != null ? account .Name : null;

The Safe Navigation Way!

String accountName = account?.Name

Remember it is not just limited to the account object, you can use it any reference in the apex. Just make sure that the return type is correct. 

Ok, now you have the basic idea of this cool operator, let's explore more examples. 

Example 2:

What if you are calling a method from an object which can be null?

anObj[x].aMethod()?.aField 

This example returns null if anObj[x].aMethod() evaluates to null.

Example 3:

This example shows how the method call is skipped if the object is null.

Integer = anObj?.getCount();

Example 4:

Replace the if block!

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

Example 5:

Now, this is my favorite! We can use the Safe Navigation Operator in the single-row SOQL query.

// Previous code checking for nulls
contacts = [SELECT Name FROM Contact WHERE Id = :contactId];
if (contacts.size() == 0) {
    return null;
}
return contacts[0].Name;

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


Final words

Well done Salesforce! This operator will definitely improve the code readability. It will reduce cyclic complexity. Simply, this will allows us to write and read more logic in less code. This is my favorite update in Winter 2021 release! 

What is your favorite feature from Winter 2020 release? 


References

3 comments:

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com