Simplify Null Checks in Apex with New ?? Null Coalescing Operator

Handling null values in code often requires verbose checks and boilerplate logic that clutter up your neat Apex classes or triggers. With Salesforce’s Spring ’24 release, there’s now an elegant shortcut to replace all those if/else statements or ternary operators – introducing the null coalescing operator (??).

Advertisements

What is the Null Coalescing Operator?

The null coalescing operator (??) allows you to shorten the syntax for dealing with possible null values in your code. Here is a simple example:

Integer value = myVariable ?? 100;

This checks if myVariable is null. If it is not null, value will be set to myVariable. But if myVariable is null, value will default to 100 instead.

The syntax is clean and easy to read at a glance. The left side is checked for null, while the right side defines a default value to use if null is found.

How Does the Null Coalescing Operator Work?

Under the hood, the ?? operator follows this logic:

  1. Evaluate the left side expression (myVariable above)
  2. If it is NOT null, return that value
  3. If it IS null, then evaluate and return the right side expression instead (100 above)

A few key notes on how it operates:

  • The left side expression is evaluated only once
  • The right side expression is only evaluated if needed (when left side is found null)
  • Both sides must be compatible data types, just like any binary operation

The end result is null check logic condensed down to a simple, readable operator.

Comparing Syntax Before and After This Feature

To fully appreciate how much cleaner your code can become, it helps to compare what verbose null checks used to look like versus the streamlined ?? operator.

Before Null Coalescing Operator

Here is code you may recognize from validating and providing default values when things are null:

// Long hand validation check
String username = getUsernameFromDatabase(); 
if(username == null) {
  username = 'default_user'; 
}

// Shorthand with ternary operator 
String username = (getUsernameFromDatabase() == null) ? 'default_user' : getUsernameFromDatabase();

While handy, the ternary operator can still be messy when chained or nested:

Integer value = (input1 != null) ? input1 : ((input2 != null ) ? input2 : ((input3 != null) ? input3 : 100));  

You have to verify each input for nulls all the way down the line before defining a default.

After Null Coalescing Operator

Now contrast those previous examples with using the new ?? syntax:

String username = getUsernameFromDatabase() ?? 'default_user';

Integer value = input1 ?? input2 ?? input3 ?? 100;

The logic and intent become far more readable at a glance. No extra syntax noise required!

Advertisements

Use Cases for the Null Coalescing Operator

Now that you understand how it works under the hood, where will this new operator shine in your Salesforce app development?

Here are some common use cases and examples where ?? cleans things up.

1. Default Values for Variables

A perfect use case is defaults when source values turn up null:

// Default account name if the input is null 
Account account = getAccountFromDatabase() ?? new Account(Name='My Default LLC');

// Default number value if various inputs are null
Decimal value = input1 ?? input2 ?? input3 ?? 0; 

No longer a need for nested ternary checks!

2. Null-Safe Chaining

The null coalescing operator allows simple chaining to safely access nested properties. If any part along the chain returns null, it gracefully falls back to the default instead of bombing out.

// Safely check street of account's child contact's mailing address 
String street = account.PrimaryContact.MailingAddress.Street ?? 'No Street Available';

3. Wrapping SOQL Queries

SOQL queries pose a common “risk” of no returned rows. Traditionally you have to wrap them in if/else checks:

Account myAccount = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1];

if(myAccount != null ) {
  // Do something with myAccount
} else { 
  myAccount = new Account(Name='Default'); 
} 

Now SOQL results can be null-coalesced directly:

Account myAccount = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1] ?? new Account(Name='Default');

Clean abstraction of that previous anti-pattern!

4. Coalescing Constructor Parameters

For any method or class constructors that take optional parameters, default values are simpler than ever:

// Constructor allowing optional params with defaults  
public MyClass(Integer input1, Integer input2, Integer input3){
  input1 = input1 ?? 0;
  input2 = input2 ?? 10; 
  input3 = input3 ?? 100;

  // Do something with inputs  
}

// Usage: Any params can remain null and coalesced
MyClass instance = new MyClass(null, 30, null); 

This constructor handles all nulls gracefully without needing overloaded methods.

When to Avoid the Null Coalescing Operator

While extremely useful, you should keep a few “code smells” in mind as red flags to avoid misapplying the null coalescing operator.

Watch out for these anti-patterns when thinking in terms of ??:

Side-Effects Could Cause Issues

The left side expression does get evaluated once before checking for null. So if it happened to have side-effects each time it ran, those would still occur.

// Avoid - the method gets called twice if null!
Integer value = getNextVal() ?? 100;  

// Better 
Integer tmp = getNextVal();
value = tmp ?? 100;

Fallback Value Should Imply Expected Type

Both sides must share compatible data types. But additionally, for readability you should ensure the right side fallback also sets the expected type clearly.

For example, avoid:

Account myAccount = [SOQL] ?? new Contact();

Even if technically valid, this wrongly implies fallback will be an Account instance. Use contextual defaults instead:

Account myAccount = [SOQL] ?? new Account(Name='My Default LLC'); 

Can Obscure Some Null Checks Needed

You still want to validate inputs explicitly on any public methods or integration boundaries:

// Avoid assuming null check protection externally
public void myMethod(String input) {
  String value = input ?? 'hello';

  // Danger - input could be null still before ?? operator! 
  System.debug(input.length()); 
}

// Better check first 
public void myMethod(String input) {

  if(input == null){
     // Handle null input  
     return;
  }

  String value = input ?? 'hello'; 

  // Now safe to use input  
  System.debug(input.length());
}

While concise syntax, ?? won’t do your complete null-safety validations for you!

Advertisements

Summary and Key Takeaways

The newly introduced null coalescing operator marks an elegant leap forward in handling null values gracefully in Apex code for Salesforce developers.

Let’s recap some key highlights:

  • Condenses verbose conditional checks and default values inline
  • Returns left side operand if not null, otherwise returns right side
  • Shorthand helps clean up clutter related to null checking
  • Shines when assigning defaults safely and concisely
  • Careful not to misapply and ignore needed validation checks

Overall this operator fits nicely alongside other recent improvements like optional parameters and null safe object chaining.

Adopting the ?? syntax will help reduce technical debt in your codebase and allow more fluent expression of fallback business logic without compromising readability. Your future self maintaining that code will thank you!

Give the new null coalescing operator a try today and let that cleanly abstracted code speak for itself.

About the blog

SFDCLessons is a blog where you can find various Salesforce tutorials and tips that we have written to help beginners and experienced developers alike. we also share my experience and knowledge on Salesforce best practices, troubleshooting, and optimization. Don’t forget to follow us on:

Newsletter

Subscribe to our email newsletter to be notified when a new post is published.

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

This Post Has 2 Comments

  1. Alon

    I’m pretty sure the example you have for Coalescing Constructor Parameters is wrong. The constructor you wrote takes three parameters, but when you call it, you only send two. When I first read this, I thought you were saying that you could do this now because of the new operator, but you can’t. Sure, you can send null values that coalesce, but you still need to use the appropriate method signature (sending three values if it expects three values, even if they’re null).

    1. Arun Kumar

      You are correct, when calling a constructor, we must match the number of arguments expected in the defined signature, even if passing nulls for some values.

      MyClass instance = new MyClass(null, 30, null);

      Thank you sincerely for catching mistake in code snippet.

Leave a Reply