Best practices for trigger formulas

Triggers use formulas to calculate conditions, change field values, or perform other logic. To write efficient formulas, follow these guidelines:

  1. Use the return keyword only in complex formulas with intermediate variables:
    • Efficient:
      ({!amount} > 1000)
    • Inefficient:
       if ({!amount} > 1000)
            return true;
       else
            return false;
  2. Avoid looping through related records. Use group functions instead (looping through related records can seriously affect performance).
  3. Always use integration codes instead of IDs for status and picklist items (this applies to template fields and formula fields as well). Logic based on IDs will not work correctly in applications published to other tenants because the IDs change.
  4. In the trigger formula, if we are altering any data on After Delete timing, ensure that it is not a large job or a delayed job
  5. Avoid manipulating any data in the current record of any After Delete trigger timing when the trigger is configured to run as a large or delayed job. On such trigger runs, the record may not be found as it is already deleted.
  6. Ensure After Delete trigger timing is used only for synchronous trigger runs.