Tuesday, December 1, 2020

Safe Navigation Operator – Avoid Null Pointer Exceptions

Safe Navigation Operator (?.) first evaluates the Left-Hand-Side of the chain expression. If it is NULL, the Right-Hand-Side is evaluated and returns NULL. We can use this operator in variable, method, and property chaining.

To use the Safe Navigation Operator, we just need to replace the dot (.) with “?.“.

For Example,  Account?.Type.

Example: 1

// Creating a NULL reference.
Account objAcc; 

// it throws Null Pointer Exception.

// it prints the NULL because we used the safe operator

Example: 2

Without Safe Navigation Operator:

String str = 'Salesforce Code Crack';

With Safe Navigation Operator:

String str = 'Salesforce Code Crack';

Example: 3

Without Safe Navigation Operator:

list<Account> lstAccs = [SELECT Type FROM Account WHERE Id='0013z00002TAEwaAAH'];
if(lstAccs != null && !lstAccs.isEmpty()){

With Safe Navigation Operator:

System.debug([SELECT Type FROM Account WHERE Id='0013z00002TAEwaAAH' LIMIT 1]?.Type);


No comments:

Post a Comment