With Salesforce’s Spring ’24 release, Null checks in Apex got simplified with this Null Coalescing Operator(??).
The ?? operator returns the left-hand argument if the left-hand argument isn’t null. Otherwise, it returns the right-hand argument.
You must ensure type compatibility between the operands.
For example, in the expression: objectZ = objectA ?? objectB, both objectA and objectB must be instances of objectZ to avoid a compile-time error.
Before Spring ’24 release, there was if/else statements or ternary operators like below.
Integer notNullReturnValue = (anInteger != null) ? anInteger : 100;
Now, with the Null Coalescing Operator, use:
Integer notNullReturnValue = anInteger ?? 100;
Handling SOQL
Account myAccount = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1] ?? new Account(Name='Default');
Handling Variable
// Default number value if various inputs are null Decimal value = input1 ?? input2 ?? input3 ?? 0;
Benefits of Using the Null Coalescing Operator
Cleaner Code: The null coalescing operator makes the code more readable and concise compared to traditional if-else statements or ternary operators for null checks.
Abstracting Logic: It abstracts the null-checking logic, making the codebase cleaner and easier to maintain.
Conclusion
By using the null coalescing operator, you can simplify your code and handle potential null values more gracefully. This can be particularly useful in scenarios where default values are needed for null or unset variables.