function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BabugarhBabugarh 

Triggers - Best Practice

Hi

 

I was looking at if there are any good practices in using triggers.

 

Say, should I slice down all the code in a trigger and move it across into a class/controller ?

 

If I were to use more of the trigger's features like trigger.oldmap or trigger.newmap or trigger.new or trigger.old.  Is it still a good practice to still move these into the controllers (through assignments) to functions?

 

If you think that those are not good practices, please do let me know.

 

This question is in regard with long term maintenance perspective. 

nnewbold-sfdcnnewbold-sfdc

The best thing you can do regarding triggers is to follow the standard bulkification pattern:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_patterns_bulk.htm

 

Otherwise, standard design patterns, such as Facade, Decorator, Factory, etc., should help you design your solutions for maintainability.

BrianWKBrianWK

Original, whenever we needed new functionality through a trigger -- we would create a new trigger named after the functionality with the

 

Example: Account_Update_Contract_Amt_Trigger

 

The benefit was it was easy to find the specific Trigger you were looking for

The problem with this method was it didn't scale very well and we grew and added more functionality. We also began having issues with the process. Since you don't have control over the order every trigger fires - it became unwieldly on certain objects that had many triggers.

 

We're currently moving to a different system. Most of our "Work" is done in classes. The Triggers themselves simply parse the information and pass it to various classes.

 

So our triggers are named to like: Account_Before_Update, and Account_After_Insert.

 

This means we would have 6 triggers - at the most - for any given object (Before/After Update, Before/After Insert, Before/After Delete).

 

Within the trigger we have our logic to determine what happens to each Trigger.new record. We build Lists of sObjects and Sets of IDs and pass them to various classes which do the actual work.

 

So far this has been very helpful and makes the system easier to manage.