Apex Trigger Best Practices

By in
947
Apex Trigger Best Practices

When writing apex triggers, there are a lot of things to consider. Neglecting apex trigger best practices could lead to multiple production exceptions.

 

Best Practices

apex trigger best practices

 

  1. Always write one trigger per object.
    • Multiple triggers on one object have a serious problem. You have no way to know which trigger will execute first. No sequence is pre-determined.
  2. Always use helper classes.
    • Helper classes help in refactoring the code. This is super important for big enterprise-level developments.
  3. Try to reuse code as much as possible.
    • You shouldn’t write code that’s already been written by you or some other developer. There’s a principle called DRY. It means Do not Repeat Yourself.
  4. Breakdown your methods to the minimum level possible.
  5. Try using Trigger Frameworks for a heavy code base.
    • There are many trigger frameworks available based on the use case.
    • Trigger Framework helps to follow all the best practices.
    • Trigger Frameworks have features like re-entry, recursion, bypass, etc.
    • There are mainly 3 types of trigger frameworks available. Mid-level, Beginner level, and Advanced level. Which one to use can be decided based on the scale of the development that will be done.
  6. Avoid reentry into any trigger method.
  7. Avoid recursion as much as possible.
    • Recursion can happen if a trigger is being called multiple times without a stop condition. You can use Trigger Frameworks to take care of this for you.
  8. Use the future methods for making callouts to an external system.
  9. Use Apex Design Patterns.
  10. Make sure to use before events to update the trigger values by default.
  11. Keep in mind the context of static in before and after triggers.
  12. Bulkify your code.

 

Conclusion

In this way, always focus on best practices while writing apex triggers to make sure you don’t run into exceptions at run time. As Salesforce is a multi-tenant architecture, triggers can become very heavy in terms of operations if not written properly.

 

For additional info on Apex Triggers, check out more of my related blogs below!

 

Additional Resources

Cover Photo by Clark Young on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *