Apex Programming – Safe Navigation Operator

Sometimes Apex throws an attempt to de-reference a null object when trying to access an object in this way

String prospectPhone = appointment.Prospect__r.Phone__c;

this exception happens when my appointment doesn’t have a Prospect assigned and it tries to retrieve a Phone from a null Prospect and Apex throws an exception.

It is annoying….. right?

Now with the Safe Navigation Operator, it’s possible to avoid this kind of exception.

How is it possible…..?

See the updated code

String prospectPhone = appointment.Prospect__r?.Phone__c;

we use “?.” instead of “.”, this way, we check that Prospect__c is not equal to null in the appointment, if this is true, it will return Phone.

If it is false, it will return null, avoiding having an exception while trying to get a Phone from a null object.