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
Tom Guo 19Tom Guo 19 

Trigger and Class Structure Best Practice with Filters

My question is around asking what is the best practice when it comes to implementing Triggers to only fire when certain fields change and how to incorporate more filters in a manner that is efficient and aligns with best practices.  

For example, I have a Trigger on Contract which fires only when a checkbox field -> Apply Billing Frequency to All Lines is changed. In this case, if it is changed, the class and method ContractTriggerHandler.handleBeforeUpdate fires:
trigger ContractTrigger on Contract (before update) {
    
    if(Trigger.isBefore && Trigger.isUpdate){
        // Contract.Apply_Billing_Frequency_to_all_Lines__c has been Changed
        List<Contract> filteredContracts = new List<Contract>();
        for(Contract newContract: Trigger.new){
            Contract oldContract = Trigger.oldMap.get(newContract.Id);
            if(newContract.Apply_Billing_Frequency_to_all_Lines__c!=oldContract.Apply_Billing_Frequency_to_all_Lines__c){
                filteredContracts.add(newContract);
            }
        }
        ContractTriggerHandler.handleBeforeUpdate(filteredContracts);
    }
    
}
My questions are as follows: 

1) To confirm, these filter criteria should be implemented on the Trigger and not the Class correct? 
2) Do I write the same logic for each different condition? For example, if I want to add to my Trigger and have it only fire when Contract.Some_Custom_Field_c changes, I'll write within this same trigger another conditional checking values of the old map with the new map and see if the Contract.Some_Custom_Field_c has been changed. Is there a more efficient way of doing this? 
3) I'm guessing as I add this code where I want the trigger to only fire when specific changes are made, I'll have to be more specific in my class methods so that I don't only have handleBeforeUpdate handling everything that is in this case handling changes when Trigger.isBefore and Trigger.isUpdate. Any advice/ best practice guidelines on how to segment the methods within the class? 

Thank you for your help. 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Tom,

I tried searching but as you have mentioned that was the only way I could find wherein you would be comparing the values from old map with the values from the new map link: if(trigger.newMap.get(a.Id).Name != trigger.oldMap.get(a.Id).Name)

Also, for general best practices, you could follow these mentioned in the link (https://developer.salesforce.com/forums/?id=906F0000000DBl8IAG), these should be good enough for any trigger that needs to be implemented.

I hope this answers your questions if not let me know I will try checking once more.

Regards,
Anutej