The Spring ’24 release of Salesforce brings the null coalescing operator (??) to Apex, making it easier to handle null values. This operator streamlines conditional checks. It also enhances code clarity. This provides a more concise and safe way to set default values.
What is the Null Coalescing Operator?
The null coalescing operator ??, is a binary operator in the form a ?? b. It returns:
aifaisn’t null.- otherwise
b.
This operator is left-associative, meaning it evaluates from left to right.
Benefits of Using the Null Coalescing Operator in Apex
- Enhanced Readability: Simplifies code by reducing the need for verbose null checks.
- Improved Maintainability: Makes the code base cleaner and easier to understand.
- Efficient Default Assignments: Provides a concise way to assign default values when variables are null.
Let’s see some the examples –
Example 1: Using the Null Coalescing Operator in Apex with SOQL Queries to Fix no rows for assignment Exception
Suppose we want to retrieve an Account record using a SOQL query. If the query didn’t return any result, we used to get “System.QueryException: List has no rows for assignment to SObject”
Before –
Account a ;
a = [SELECT Id FROM Account WHERE Name = 'Test' LIMIT 1];
/*System.QueryException: List has no rows
for assignment to SObject will be thrown*/
if(a!=null) {
System.debug(a);
} else {
// do something
}


After –
Let’s see , how we can utilize the null coalescing operator to handle cases where no records are returned.
Account a;
a = [SELECT Id FROM Account WHERE Name = 'Test' LIMIT 1]
?? a;
System.debug(a);
// will not run, as account is null
// No System.QueryException: List has no rows
//for assignment to SObject will be thrown
if(a!=null){
System.debug('a+++'+a);
}
or if you want to assign default value
Account a;
a = [SELECT Id FROM Account WHERE Name = 'Test' LIMIT 1]
?? new Account(Name='Default');
System.debug('a+++'+a); //Account:{Name=Default}
Example 2: Assigning Default Values
Consider a scenario where you have a variable that might be null, and you want to assign a default value if it is:
Integer userAge = null;
/* If userAge is null,
age will be 18*/
userAge = userAge ?? 18;
Integer userAge = 21;
// userAge will be 21
userAge = userAge ?? 18;
Example 3: Simplifying Conditional Assignments
Before the null coalescing operator, handling null values often required verbose conditional statements:
String username;
if (inputUsername != null) {
username = inputUsername;
} else {
username = 'defaultUser';
}
With the null coalescing operator in apex, this can be simplified to:
String username =
inputUsername
?? 'defaultUser';
4. Converting Ternary operator (? : ) to Null Coalescing Operator (??) –
Before
Integer value =
(intValue != null)
? intValue : 100;
After
Integer value =
intValue ?? 100;
Example 5: Chaining with the Null Coalescing Operator
Suppose you have three optional integer variables, and you want to assign a non-null value to a result variable, defaulting to 100 if all are null:
Integer value1 = null;
Integer value2 = null;
Integer value3 = 50;
Integer result = value1 ?? value2 ?? value3 ?? 100;
System.debug('Result: ' + result);


The expression value1 ?? value2 ?? value3 ?? 100 evaluates as follows:
value1isnull, so the operator moves tovalue2.value2isnull, so the operator moves tovalue3.value3is50, which is notnull, soresultis assigned the value50.
If all variables (value1, value2, and value3) were null, result would be assigned the default value of 100.
Consideration while using the Null Coalescing Operator –
You need to be conscious and consider some of the below anti patterns while using it.
1. Avoid Side Effects in Left-Hand Expressions
The left-hand expression is always evaluated before checking for null. If the expression involves method calls, these actions will still occur. Operations that have side effects will also happen regardless of the null check.
Problematic Code:
// The method fetchAccountName() gets called twice if it returns null
String accountName = fetchAccountName() ?? 'Default Account';
Improved Code:
// Store the result in a variable to ensure the method is only called once
String fetchedName = fetchAccountName();
String accountName = fetchedName ?? 'Default Account';
In this example, fetchAccountName() might perform a query or other operation. Storing the result ensures the operation happens only once.
2. Provide Contextually Appropriate Fallback Values
The fallback value in the null coalescing operation should match the compatible data types. Using an in compatible fallback can create errors.
Problematic Code:
/* error will come - Incompatible types in null coalescing operator:*/
List<Account>, Contact
Account myRecord = [SELECT Id, Name FROM Account WHERE Name = 'Test' LIMIT 1]
?? new Contact();
Improved Code:
Account myRecord = [SELECT Id, Name FROM Account WHERE Name = 'Test' LIMIT 1]
?? new Account(Name = 'Default Account');
3. Don’t Skip Explicit Input Validation
While the null coalescing operator simplifies assigning default values, it doesn’t replace proper validation. This is particularly important in public methods or triggers.
Problematic Code:
public void processCase(String caseId) {
String idToUse = caseId ?? '500NS00000QfjNNYAZ';
// Risky: caseId might still be null here
System.debug('Case ID length: ' + caseId.length());
}
Improved Code: Explicit validation ensures caseId is handled appropriately before proceeding with logic that relies on its value.
public void processCase(String caseId) {
if (caseId == null) {
System.debug('Error: No Case ID provided.');
return;
}
String idToUse = caseId ?? '500NS00000QfjNNYAZ';
// Now it's safe to use caseId
System.debug('Case ID length: ' + caseId.length());
}
4. Can’t use on the left side of assignment
You can’t use the null coalescing operator as the left side of an assignment operator in an assignment.
- foo??bar = 42;// This is not a valid assignment
- foo??bar++; // This is not a valid assignment
5. Not Supported by SOQL bind expressions
SOQL bind expressions don’t support the null coalescing operator.
String primaryName;
String secondaryName = 'Acme';
String acctName = primaryName ?? secondaryName;
List<Account> accounts = [SELECT Name FROM Account WHERE Name = :acctName];
List<List<SObject>> moreAccounts = [
FIND :acctName
IN ALL FIELDS
RETURNING Account(Name)
];
Apex developers can write more efficient code by utilizing the null coalescing operator. It makes the code more readable when dealing with potential null values.


Leave a comment