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.

Apex Programming – Null Coalescing Operator

Do you know that you can simplify the use of the ternary operator while checking null values in Apex programming?

Previously, we had to write this whole syntax for the ternary operator to do an assignment

fullName =  patient.fullName != null ? patient.fullName : "TBD";

Now, it is simplified using the Null Coalescing Operator

fullName = patient.fullName ?? "TBD";

this binary operator ?? will check if the left-hand side value is not equal to null and will return that if it is true. OR it will return the right-hand side value of the operator.