Top 10 Apex Updates in Salesforce Spring 24 Release

Top 10 Apex Updates in Salesforce Spring 24 Release

Apex, the programming language of Salesforce, is constantly evolving to meet the needs of developers and customers. In the Spring '24 release, you'll find new Salesforce Spring ‘24 release features and Apex updates aimed at boosting power, flexibility, and user experience.

Take advantage of this Salesforce Apex developer guide to enable these updates in your Salesforce projects.

1. The Null Coalescing Operator

Salesforce has added a new apex feature– the Null Coalescing operator (??) to replace verbose and explicit checks for null references in code. This returns the left-hand argument unless it's null, in which case it switches to the right-hand argument.

public class NullCoalescingExample {
    public static void demonstrateNullCoalescing() {
        // Assume these variables are set elsewhere in your application
        String primaryEmail = null;
        String secondaryEmail = 'secondary@example.com';

        // Without the null coalescing operator, you might use an if-else statement
        String emailToUse;
        if (primaryEmail != null) {
            emailToUse = primaryEmail;
        } else {
            emailToUse = secondaryEmail;
        }

        // With the null coalescing operator, you can simplify the above logic
        String emailToUseSimplified = primaryEmail ?? secondaryEmail;

        System.debug('Email chosen (traditional way): ' + emailToUse);
        System.debug('Email chosen (with null coalescing): ' + emailToUseSimplified);
    }
}
Where: This change applies to all Salesforce editions.

2. Improved Validation with DML on External Objects

DML (Data Manipulation Language) operations are used to insert, update, delete, and query records in a database. Starting from Spring '24, exclusive access to DML methods, such as Database.insertImmediate() and Database.insertAsync(), is granted to external objects only. Attempting to use these methods with other object types will result in a catchable TypeException.

3. Support for Randomly Generated UUID v4 

UUIDs are generated to ensure uniqueness across different systems and applications, making them suitable for various purposes, such as creating unique identifiers for objects or records in distributed databases, uniquely identifying resources on the internet, and more.

In the Spring 24 release, Salesforce introduced a new UUID class to generate a version 4 universally unique identifier (UUID), making resource identification more easier than ever.

Where: This change applies to all Salesforce editions.
How: To generate a UUID and perform operations on a UUID instance, you can use these methods in the UUID class.
  • randomUUID()-Randomly generates a UUID that uniquely identifies an object.

  • equals(obj)-Compares the UUID instance with the specified object. Returns true if both are equal; otherwise, returns false.

  • hashcode()- Returns the hashcode corresponding to the UUID instance.

  • fromString(string)- Returns a UUID instance from a string representation of a UUID.

  • toString()- Returns the string representation of the UUID instance.

Here’s an example that uses the randomUUID() class method.

UUID randomUuid = UUID.randomUUID();
// Prints the UUID string that was randomly generated
system.debug(randomUuid);

String uuidStr = randomUUID.toString();

UUID fromStr = UUID.fromString(uuidStr);

Assert.areEqual(randomUuid, fromStr);

4. New Default Quiddity Enum Value

Spring '24 brings a new default quiddity value, undefined (UD), for events lacking a descriptive quiddity. This replaces the old default, Synchronous Uncategorized (R), and simplifies event handling with a clearer default.

Where: This change applies to all editions and is a versioned behavior change in API version 60.0 and later.

5. Evaluate Dynamic Formulas in Apex (Developer Preview)

Dynamic formulas in Salesforce are needed to evaluate formulas for Apex and sObjects, which helps in reducing unnecessary DML statements for formula recalculations and dynamic expressions.

Now you can use the FormulaEval namespace to evaluate formulas for Apex and sObjects, reducing unnecessary DML statements for formula recalculations and dynamic expressions.

Where: This feature is available in scratch orgs where the FormulaEvalInApex feature is enabled. If the feature isn’t enabled, Apex code with this feature can be compiled but not executed.
How:
a) To create an instance of the formula, call the static method builder() in the FormulaBuilder class by specifying the formula text, return type, and context object. 
b) To validate the formula instance, call the build() method. If the validation fails, the build() method triggers the FormulaValidationException exception.
c) To calculate the formula expression and return the result, use the evaluate() method in the FormulaInstance class. If the evaluation results in an error, the method triggers the FormulaEvaluationException exception.

6. Make Callouts After Rolling Back DML and Releasing Savepoints 

You can now make callouts after undoing uncommitted DML with savepoints. Use Database.releaseSavepoint to release savepoints before callouts. This is needed because releasing savepoints before callouts ensures that the database state is consistent and doesn’t contain uncommitted DML operations, avoiding any conflicts or inconsistencies during the callout operation.

How: To allow callouts, roll back all savepoints and explicitly release them. Below is an example to help you understand better. Here, the makeACallout() callout succeeds because the uncommitted DML is rolled back and the savepoint is released.
Savepoint sp = Database.setSavepoint();
try {
// Try a database operation
insert new Account(name='Foo');
integer bang = 1 / 0;
} catch (Exception ex) {
Database.rollback(sp);
Database.releaseSavepoint(sp); // Also releases any savepoints created after 'sp'
makeACallout(); // Callout is allowed because uncommitted work is rolled back and savepoints are released
}

7. Enforce RFC 7230 Validation for Apex RestResponse Headers (Release Update)

Before this update, Salesforce Apex REST Response headers weren't validated, potentially leading to compliance issues and unforeseen behavior. After this update is enabled, regardless of the API version, REST response headers defined in Apex via the RestResponse.addHeader(name, value) method will have header names validated based on RFC 7230. 

Where: This change applies to all Salesforce editions.
When: Salesforce enforces this update in Spring ’24. To get your instance's major release upgrade date, go to Trust Status, search for your instance, and click the Maintenance tab.
How: Apex calling RestResource.addHeader(name, value) with a non-RFC 7230-compliant header name triggers an InvalidHeaderException. Ensure all packages are compatible before activating this update and assess its impact on your Salesforce organization.

Evaluate the impact on your Salesforce org with these checks.

  • Run Apex test cases and check for failures caused by InvalidHeaderExceptions.

  • Invoke your Apex REST API classes and check responses for InvalidHeaderException exceptions.

  • Inspect Apex code that calls the RestResource.addHeader(name, value) method for a name parameter with a value that isn’t RFC 7230-compliant.

8. Improved Logging When FOR UPDATE Locks Are Released

Salesforce enhances record-lock logging in Salesforce Apex using FOR UPDATE, especially with callouts. The debug log now includes details on released locks and the latest unlocked entity type, improving record-locking process visibility.

For example, the debug log offers details regarding released locks:

FOR_UPDATE_LOCKS_RELEASE FOR UPDATE locks released due to a callout. The most recent lock was Account.

9. Changed Behavior with Type.forName Method

Salesforce has enhanced the consistency of the Type.forName() method this Spring. This method is employed in Salesforce to fetch the type of an Apex class, whether a built-in or user-defined class. It proves valuable for generating dynamic instances of classes implementing an interface. 

Now, if an invalid namespace is utilized, the method will return null.

Where: This change applies to Salesforce orgs in all editions. This change is a versioned behavior change in API version 60.0 and later.

10. New namespace for AppExchange App Analytics

Lastly, Salesforce introduced a new namespace for AppExchange App Analytics with methods like logCustomInteraction. This is Salesforce’s attempt to enable AppExchange partners the capability to track and analyze how their customers use their solutions. With this insight, ISVs can further improve user experience and retention for their products/services.

When is the Salesforce Spring 24 Release Date?

The Salesforce Spring 24 release date depends on your SF instance; however, the major release weekends are on Jan 12, Feb 2, and Feb 9 weekends. Do test out all of these updates and main use cases in your org before these dates so you can ensure a hassle-free workflow afterward.

Conclusion

The Salesforce Spring '24 Release features a wave of exciting Apex updates for developers and Salesforce users. At Concretio, we are keeping a close check on all of the Salesforce Apex updates and have already started testing/implementing these to enhance the experience of businesses. Let our team be your trusted partner in navigating this exciting evolution and building the future of your Salesforce applications.

References:

  1. Make Callouts After Rolling Back DML and Releasing Savepoints

  2. IdeaExchange Delivered: Get Support for Randomly Generated UUID v4

Previous
Previous

Make Callouts After DML Rollback and Savepoint Release[Explained]

Next
Next

Top 10 Admin Updates in Salesforce Spring ‘24 Release