This post is part of the series – Design Pattern in Apex

I know it was discussed number of times earlier about Apex Trigger Design Pattern. Below are few excellent posts –

I 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 code
  • Follow Salesforce Best Practice – One Trigger per object
  • Follow another Salesforce Best Practice – Move all code from Trigger to Apex Classes – Handler Classes
  • Ability 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 – AccountTriggerHandler

And finally the trigger – AccountTrigger

Now 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 AccountTriggerHandler

Use Case 2 –
While updating accounts, if Account Name changed, find how many account name changed and print the count.
Implementation –
To implement the above requirement, what we need to do is simply add the functionality in AccountTriggerHandler.AccountBeforeUpdateHandler class. You can do the same in AfterUpdate also. 🙂
Here is the updated AccountTriggerHandler

Please provide your feedback. Thanks.