Missed opportunity: Safe navigation operator
Why is this an issue?
NullPointerExceptions (NPEs) are common in Apex. The safe navigation operator (?.) provides a cleaner way to handle potential null values in method chains, reducing verbose null checks.
Examples
Example of incorrect code:
String city;
if (account != null && account.BillingAddress != null) {
city = account.BillingAddress.getCity();
}
Example of correct code:
String city = account?.BillingAddress?.getCity();
The safe navigation operator returns null if any element in the chain is null, instead of throwing an exception.
How can I fix violations?
This rule supports autofix.
Replace null-check chains with the safe navigation operator:
// Before
if (obj != null && obj.getRelated() != null) {
return obj.getRelated().getName();
}
return null;
// After
return obj?.getRelated()?.getName();
When should I disable this rule?
You may dismiss specific violations when you need to distinguish between "value is null" and "parent is null" for different handling.
Resources
