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
Null check Using Safe Navigation Operator
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.
or can be also used on top level check
or using parenthesis while casting
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.
- Namespaces
- 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;
- It also can't be used in SOQL Binding expressions like
- class X { public String query = 'xyz';}
- X x = new X();
- List<Account> accounts = [SELECT Name FROM Account WHERE Name = :X?.query]
- List<List<SObject>> moreAccounts = [FIND :X?.query IN ALL FIELDS
- RETURNING Account(Name)];
- With addError() on SObject scalar fields. For example:
- Contact c;
- c.LastName?.addError('The field must have a value');
- However it can be used on Sobjects like
- Contact c;
- 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
Post a Comment