As a developer, we have often run into scenarios where we are doing some assignments, running parent object queries, etc. but forget to do a null check. As a result we get a NullPointer Exception.
To avoid this, we have to explicitly do some checks, thus increasing our lines of code.
With the Safe Navigation Operator (?.), Salesforce now gives the developers the option to do the null checks (in some scenarios) in a single line. This simplifies the readability and reduces the lines of code.
In short a?.b // Evaluates to: a == null ? null : a.b
Let’s go through a use case (really its just for explaining and thus a very simple case). I want to replace the “Case” Subject with the first letter of Account Name, else make it null. Just to explain the difference, I have queried only 2 case records.
So to start, here is a small block of code
The moment I execute this I get a NullPointer Exception.
If I check the debug logs, I see the error is on the line containing the cs.Account.Name.left(1)
Even though I queried Account.Name, it gives an exception as one of the case records did not have Account lookup populated.
A few ways to avoid this can be
- Do null check before assignment
- Assign a string variable through a ternary operator
- Check using String.IsNotBlank (as Account Name is string)
Adding a String.IsNotBlank check, would not cause an error, but would require additional code in else, to handle the null record.
Now lets add the Safe Navigation Operator to see the result.
The code works fine and the end result is as follows :-
We could have also added ?. in front of Account.Name and that would have worked the same way.
Another example of using Safe Navigation Operator is as follows :-