Interesting ways of architecting Apex Triggers

Hello everyone!

I came across a blog post at ( about some interesting ways of architecting Apex Triggers.

We have developed a lot of logic in Apex Triggers and ended with some really nasty code in some scenarios; this post got me thinking about new ways to architect triggers using a more object-oriented approach. So just to follow the thoughts in this post I'll show you what I did to organize our triggers and it has been working pretty good so far.

NOTE: Please refer to the code section below

//Step 1

I started by creating an Apex Class to replicate some of the triggers functionality...

//Step 2

The next step will be to start coding our Apex Class that will perform all of the logic in our triggers, so let's say the we are building a trigger for My_Object__c custom object.

//Step 3

And finally, we just need to create the Apex Triggers that will just initialize our Trigger class and initialize an instance of the corresponding Apex Class that will handle all of the logic.

And that's it! Just remeber to cast the the collections correctly before accessing the collections from the ExtTrigger class because we can't work with generic sobject collections.

Some of the benefits that I've seen by organizing Apex Triggers in this way are the following:

  • 100% Test Coverage in Apex Triggers (although all of the Test Coverage should be done in the handler Apex Class)

  • Since we can call functions to perform specific actions in Apex Classes, we end up with more organized code, it's easier to read in the sense that you can just go to see the calls inside the "onBeforeInsert" section for example..

  • Avoid the max number of characters governor limit:

    • Maximum number of characters for a class: 100,000

    • Maximum number of characters for a trigger: 32,000

Thanks to everyone that posted in gokubi's blog post any feedback on this is appreciated :)


  1. [...] gokubi and jonathanrico have good posts about how to write Apex trigger codes in a best practice [...]

  2. Oops, it seems that the code is not showing up here. There seems to be an issue with the code plugin for my site, I'll try to fix it asap.


Post a Comment

Popular posts from this blog commandments object and record level security