APEX TRIGGER DESIGN PATTERN

by Sudipta Deb | Aug 11, 2015 | 501, best practice, design pattern, Trigger | 0 comments

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.

Written by

Related Posts

Restrict Uploading Files In Salesforce

Restrict Uploading Files In Salesforce

While working in Salesforce, we sometimes come up with the requirements where we need to build some sort of validation to restrict uploading files with specific extensions or in other words, allow only approved file types/extensions. This is very important because uploading executing or javascript code can bring potention security concerns by exposing internal data to outside world.

So allowing only certain type of files for upload is a very common requirement. In this blog post, I am sharing couple of solutions with pros and cons to implement this requirement.

read more...

0 Comments

Leave a Reply