Missed opportunity: Null Coalescing Operator
Why is this an issue?
The null coalescing operator (??) provides a cleaner way to handle null values compared to ternary expressions. Ternary null checks are verbose and error-prone, particularly when chained. Replacing them with ?? reduces visual clutter and makes the intent immediately obvious.
This rule detects ternary expressions where the condition is a null check and the result can be expressed with the ?? operator.
Examples
Example of incorrect code:
String name = (accountName != null) ? accountName : 'Unknown';
String name = (accountName == null) ? 'Unknown' : accountName;
Nested ternary chains are also detected:
String addr = (shippingCity != null) ? shippingCity : ((billingCity != null) ? billingCity : ((mailingCity != null) ? mailingCity : 'No city'));
Example of correct code:
String name = accountName ?? 'Unknown';
String addr = shippingCity ?? billingCity ?? mailingCity ?? 'No city';
How can I fix violations?
This rule supports autofix. The autofix replaces null-check ternaries with the ?? operator, including collapsing nested chains into a single ?? expression.
Before | After |
|
|
|
|
|
|
|
|
The autofix will not apply when:
The ternary is inside a SOQL query expression.
The nesting of ternary statements exceeds 16 levels deep.
When should I disable this rule?
This rule only fires when the condition is a pure null comparison and the branch value exactly matches the checked expression, so false positives are unlikely. You may disable it if your team prefers explicit ternary null checks for stylistic consistency.
Resources
