Safe Navigation Operator in Apex

Safe Navigation Operator is released as a part of Winter 21 update. 


Use the safe navigation operator (?.) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.



The main advantange of Safe Navigation Operator is avoid cluttered code when there are too many null checks and make it look lot  more verbose.


Let's look at an example where we might come across a Null Pointer Exception and I will show you how to use Safe Navigation Operator to make the code lot more verbose.


Step 1: 



Step 2: 

Getting the null pointer exception






Step 3:  Normal way to handle the above exception 

         


 Step 4:

        Using Safe Navigation Operator code refactor



Contact Me - 

Salesforce Hunt Social Media Handle

🔔 Subscribe to my YouTube channel

https://www.youtube.com/c/SalesforceHunt

📌Blog 

https://salesforcehunt.blogspot.com

📌FaceBook

https://www.facebook.com/salesforcehunt

📌Twitter

https://twitter.com/RohitGu83309245

📌linkedin

https://www.linkedin.com/in/rohit-kumar-81916b190/


 


Post a Comment

0 Comments