APEX TRIGGER DESIGN PATTERN
This post is part of the series – Design Pattern in ApexI know it was discussed number of times earlier about Apex Trigger Design Pattern. Below are few excellent posts -http://gokubi.com/archives/two-interesting-ways-to-architect-apex-triggershttp://www.embracingthecloud.com/2010/07/08/ASimpleTriggerTemplateForSalesforce.aspxI have learned a lot from the above two posts by Steve Andersen and Mike Leach.But the post by Abhinav Gupta really inspires me a lot and I am going to explain the pattern/template here with few use cases.The motivations for this design pattern are -Write Trigger with minimum codeFollow Salesforce Best Practice – One Trigger per objectFollow another Salesforce Best Practice – Move all code from Trigger to Apex Classes – Handler ClassesAbility to add and order multiple handlers for the same trigger event.Easy to maintain code base.Here is the Apex Trigger template – MyTriggers (Again inspired by Abhinav Gupta)Now using the above template, below is the account trigger handler – AccountTriggerHandlerAnd finally the trigger – AccountTriggerNow the trigger code is very neat and clean. At the same time all our operations against trigger events are moved to handler class.So now let’s consider few use cases -Use Case 1 -While inserting new accounts, if the Account Rating is marked as ‘Hot’, then mark those accounts as Active and make the Customer Priority as ‘Medium’.Implementation -To implement the above requirement, what we need to do is simply add the functionality in AccountTriggerHandler.AccountBeforeInsertHandler class. No changes in Apex trigger code is required.Here is the updated AccountTriggerHandlerUse...
Read More