Apex Trigger Tip: Using One Trigger Per Object To Control Logic

It was recently asked on the twitterverse how you can control the order of execution on trigger logic when you have multiple Apex triggers operating on the same object and event.  So if you have “UpdateAccountWithCase” and “UpdateAccountAfterOpportunity” as two examples, how do you know your Account will be updated with case related information before the opportunity data?

The answer is you don’t – at least not if you’ve got triggers separated out into multiple classes for a single object.  For this reason, and a few others, I’ve seen many companies utilize one trigger per data object that simply controls the flow of logic while calling the execution in other classes.  So instead of:

trigger UpdateAccountWithCase on Account (before insert, before update) {

/* execution logic */

}

trigger UpdateAccountAfterOpportunity on Account (before insert, before update) {

/* execution logic */

}

You would have one trigger, which examines the incoming event and hands off the relevant data to other classes:

trigger AccountTrigger (before insert, before update) {

if(Trigger.isBefore && Trigger.isInsert) {

UpdateAccountWithCase.handleAccount(Trigger.new);

UpdateAccountAfterOpportunity.handleAccount(Trigger.new);

}

}

 

This is short example just to illustrate, if you want to see a more robust template – check out this one from Mike Leach that Alex Berg forwarded along during the twitter conversation, which includes a full set of event handling and an example of the handler class itself.

Moving your logic from multiple triggers to a having one which controls the flow and sends it to different handler classes can take some decent refactoring, but in doing so – you’ll find that not only can you control the order of your execution, but with that you can also more reasonably track your debug processes, enable/disable specific logic from the master trigger, and hunt down which portions of the flow may be utilizing more resources than others.

Published
April 26, 2011
Topics:

Leave your comments...

Apex Trigger Tip: Using One Trigger Per Object To Control Logic