What Spring '24 added
Spring '24 gave Apex the null coalescing operator, the double question mark (??). It returns the left operand when that operand is not null, and the right operand when it is, which collapses a lot of the null-handling boilerplate you have been writing by hand.
How it works
The syntax:
operand1 ?? operand2
If operand1 is non-null it becomes the result; otherwise operand2 does. If both operands are null, the expression is null.
Common use cases
The two you will hit most are falling back to a default value and getting rid of a verbose null check. A multi-line check collapses into a single expression:
public List
if (null == contacts)
{
contacts = new List<Contact>();
}
return contacts;
}
// Becomes
public List
return contacts;
}
Chaining
Chain the operator to take the first non-null value in a sequence:
Opportunity opp = opp1 ?? opp2 ?? opp3 ?? opp4 ?? opp5;
Key considerations
- Test coverage. A single-line expression lets one unit test exercise both branches for line coverage, which makes it easy to stop there. Test both outcomes anyway, because line coverage is not behavior.
- Short-circuiting. The right-hand operand is not evaluated when the left-hand operand is non-null, which saves the work and keeps side effects from firing when you did not expect them to.
- Type compatibility. Both operands must be the same type, or promotable to a common type. Casting to a common type (for example
(sObject)) works, but it costs readability. - Readability. Do not cram a complex operation or a query into an operand.
Example: inheritance compatibility
public virtual class First { public String name { get; set; } }
public class Second extends First { }
First first = new First(); Second second = new Second(); String name = (first ?? second).name;
Further reading
The release notes, and the language-agnostic background:
Where it pays off
Used with some care, the operator removes boilerplate and makes the intent of a fallback obvious at a glance. Across triggers, controllers and Apex services, where defaults and fallbacks turn up constantly, that means fewer places for a null to slip through and less code to read later. Keep the tests explicit and the operands simple.
Leave a Comment