softvowels.com

Null Coalescing Operator

Table of Contents

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.

Recent Post

Batch Apex is usually used to build complex, long-running processes that run on thousands of records(large data volume till 50 million records), at any specific time. Go through to get concrete understanding.
Salesforce has an annotation @future that we can use defining a method making its execution as asynchronous. For concrete understanding read further.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x