Yet Another Apex Trigger Template!

I know Trigger templates were previously discussed in great detail. We have excellent posts available by Steve Andersen (Gokubi) and Mike Leach on the same. Here is my small journey on Triggers.

  • I started developing on force.com. I used the barebone approach as mentioned in the Apex developer guide.

  • After some time, I was using something similar to what Steve mentioned in his blog. I was happy to see that Steve suggested a similar practice.

  • Eventually tried something similar to what Mike suggested in his blog.

After trying all of the above trigger templates, I was still not happy when working solo or when working with a big team of engineers on the same project. I wanted something simple to adopt easily with the flexibility to extend/add as required.

So, I started working on a new trigger template with these motives in mind:

  • Framework/Base template code to start writing a new trigger should be minimal or none.

  • It should allow any complex and reusable trigger code to be written.

  • It should allow easy fixes for other commonly visible problems, like trigger firing twice.

  • Optionally create handlers with @future support.

  • Ability to easily order and add multiple handlers on a single trigger event.

Yet Another Trigger Template!

Triggers.cls” is the new trigger template. This class doesn’t need to be copied per sobject trigger and will be reused throughout the org. Here is the code snippet for it.

Using the template:

We will again follow the same trigger per Sobject rule and just write handlers for each event, like before insert, after update, etc. Handlers can be created by implementing the interface “Triggers.Handler”. The only contract of this interface is to write all the trigger logic using the trigger context variables as and when required. Here are a few sample handlers. (These handlers can be nested into one big class to avoid too many classes.)

Feedback

Looking forward to your views and thoughts on the same. I’m sure it’s a good topic to discuss and debate on.

Let’s Talk

Drop a note below to move forward with the conversation 👇🏻

Abhinav Gupta

First Indian Salesforce MVP, rewarded Eight times in a row, has been blogging about Salesforce, Cloud, AI, & Web3 since 2011. Founded 1st Salesforce Dreamin event in India, called “Jaipur Dev Fest”. A seasoned speaker at Dreamforce, Dreamin events, & local meets. Author of many popular GitHub repos featured in official Salesforce blogs, newsletters, and books.

https://abhinav.fyi
Previous
Previous

Resolved: “Field is not writeable: Sobject__Share.RowCause”!

Next
Next

Force.com ESAPI v0.5 & Death of Apex-CRUD-FLS-Validator API