Safe Navigation Operator in Apex

Hello Ohana, It's been quite some time after my last blog as i was caught up with some personal and professional engagements, But nevertheless here i am back with one of the coolest apex features that i found with Winter 21 release. I was waiting the release to go live before i post this blog and now since WI 21 is live so lets discuss how to use it. 

Before we begin with code example lets understand what exactly is safe navigation operator (?).  In very simple words it reduces the need to check for Null before accessing variable or method values which could cause Null Pointer Exception if left without checking. So now to answer the very obvious next question that "Can we get rid of all error handling and use Safe navigation Operator ?  instead" Answer is "No", what safe navigation does is instead of halting the code execution and throwing null pointer exception it simply returns null. Now lets understand it with an example. 

Old Code to return null after checking the Size

// Old code checking for nulls in Apex
contactRecord = [SELECT Name FROM Contact WHERE email = :emailId];
if (contactRecord.size() == 0) { //No Contact Match
    return null;
}
return contactRecord[0].Name;

 

Null check Using Safe Navigation Operator 

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

Here it checks if the Contact record is null so it will return null else the name of Contact matching with email will be returned. Cool right ? but this is not it, It can also be used in many other use case given below. 


String str = opportunity.Account?.someTextField;

or can be also used on top level check


String str = opportunity?.Account?.someTextField;

or using parenthesis while casting 


((T)a1?.b1)?.c1();

 remember to add safe Navigation (?)at the end of each value in our case we are checking if a1 is null or b1 is null, if we miss after any one of them  it can cause expression to fail and result in Null Pointer. 

Limitations :  As per the official Salesforce documentation below are use cases where we can't use safe navigation as of WI 20.

You can’t use the Safe Navigation Operator in certain cases. Attempting to use the 
operator in these ways causes an error during compilation:

Types and static expressions with dots. For example:
  • Namespaces
{Namespace}.{Class}
  • Trigger.new
  • Flow.interview.{flowName}
  • {Type}.class
  • Static variable access, method calls, and expressions. For example:
  • AClass.AStaticMethodCall()
  • AClass.AStaticVariable
  • String.format('{0}''hello world')
  • Page.{pageName}
  • Assignable expressions. For example:
foo?.bar = 42;
++foo?.bar;

  • It also can't be used in SOQL Binding expressions like 

  1. class X { public String query = 'xyz';}
  2. X x = new X();
  3. List<Account> accounts = [SELECT Name FROM Account WHERE Name = :X?.query]
  4. List<List<SObject>> moreAccounts = [FIND :X?.query IN ALL FIELDS
  5. RETURNING Account(Name)];

  • With addError() on SObject scalar fields. For example:

  1. Contact c;
  2. c.LastName?.addError('The field must have a value');

  • However it can be used on Sobjects like 

  1. Contact c;
  2. c?.LastName.addError('The field must have a value');

Let me know what do you think about this cool feature in comments and feel free to add any use cases if i have missed. Cheers !! Happy Learning. 




Comments

Popular posts from this blog

Flosum Certified Professional Exam Certification Process and Tips

Copado Administrator Exam Certification Process and Tips

Compare File against the Source Org in VS Code