KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Using Defer to Automatically Restore Data Selections
PRODUCT: 4D | VERSION: 21 R4 | PLATFORM: Mac & Win
Published On: November 18, 2026
4D 21 R4 introduces the new defer command. defer is a control-flow command that places code onto a special stack to be executed automatically when the current method exits, regardless of how it exits. This makes it useful for resource cleanup, state restoration, and other operations that should always occur before leaving a method.

One practical use case for defer is restoring data state. Some procedures may modify the current selection or other application state during processing. If the procedure exits early due to a RETURN statement or an unexpected error, the original state may not be restored correctly. By using defer, you can ensure the original state is restored automatically whenever the method exits.
Below is an example:
CREATE SET([myTable]; "tempSet")
defer(CLEAR SET("tempSet"))
defer(USE SET("tempSet"))

QUERY([myTable];....) // Some code ...

With this code, the original selection is restored regardless of whether the method completes successfully, exits early, or encounters an error. Deferred statements are executed in a Last-In, First-Out (LIFO) order, meaning the last defer statement registered is executed first. In this example, the USE SET operation is executed before the CLEAR SET, ensuring the selection is restored before the temporary set is removed.

There are many ways to use defer, but this example demonstrates how it can automatically handle cleanup and state restoration while helping prevent bugs caused by methods exiting unexpectedly.