Activity Forums Salesforce® Discussions What are the advantages of using Handler classes in Trigger?

  • What are the advantages of using Handler classes in Trigger?

  • Suraj

    Member
    April 17, 2017 at 2:26 pm

    What are the advantages of using Handler classes in Trigger rather writing logic in Trigger itself?

  • Saurabh

    Member
    April 18, 2017 at 11:41 am

    Hi Suraj

    It is always a best practice to write a single trigger on object and process all operation in apex class (we called it as handler) instead of writing logic in trigger. In handler you can specify the order of event based on different context variables. If you write many triggers in on object,
    then you cannot control the order in which triggers gets executed.

    For best practice, use below suggestion:

    1. Pass all trigger context variables to static method (say "OperationManager")in handler class.
    2. Create different static methods for different operations which you need to perform.
    3. Control the order of different operation in "OperationManager" static method based on context variables.
    4. Also you can create different apex classes and call them from "OperationManager" static method.

    For example, below is modified code as per best practice.
    Apex trigger code:

    trigger JobTrigger on Job__c (after delete, after insert, after undelete, after update, before delete, before insert, before update)

    {
    String errMsg = JobTriggerHandler.OperationManager(trigger.new, trigger.old, trigger.newMap,trigger.oldMap,
    trigger.isBefore,trigger.isAfter,trigger.isInsert,trigger.isUpdate,trigger.isDelete, trigger.isUndelete,trigger.isExecuting);

    // If error occured, then display it to user
    if (errMsg != null) {
    if (trigger.isInsert || trigger.isUpdate || trigger.isUndelete) { trigger.new[0].addError(errMsg); } else { trigger.old[0].addError(errMsg); }
    }
    }

    Apex class(Handler):

    public with sharing class JobTriggerHandler {
    // Main entry point for this handler.
    public static String OperationManager(list<Job__c> newList, list<Job__c> oldList, map<Id, Job__c> newMap,map<Id, Job__c> oldMap,
    boolean isBefore,boolean isAfter, boolean isInsert, boolean isUpdate,boolean isDelete,boolean isUndelete, boolean isExecuting) {
    String errMsg;
    try {
    // Only run a method if previous methods didn't fail
    //As you want to perform operation on before insert and before update
    if (isBefore && (isUpdate || isInsert) && errMsg == null) {
    // Find hourly rate by calling static method defined below
    errMsg = computeHourlyRate(newList);
    }
    //here you can call any other static methods or some other class method to perform desired operations
    //keep on adding the other logic which needs to be processed through trigger
    //through context variables you can control their execution
    } catch (Exception ex) {
    errMsg = ex.getMessage() + ' at ' + ex.getLineNumber().format();
    }
    return errMsg;
    }

    //Below method will compute hourly rate
    public static String computeHourlyRate(list<Job__c> newList) {
    String errMsg;
    try {
    Set<Id> AccID = new Set<Id>();
    Set<String> JobType = new Set<String>();
    Map<String,Rate_card__c> RateCardMap = new Map<String,Rate_card__c>();
    for (Job__c Job: newList){
    AccID.add(Job.Account__c);
    JobType.add(Job.Type__c);
    }
    For(Rate_Card__c RateCard : [SELECT Id, Hourly_Rate__c, Account__c, Type__c FROM Rate_card__c WHERE Account__c IN: AccID]){
    RateCardMap.put(RateCard.Account__c + RateCard.Type__c, RateCard);
    }
    For (Job__c Jobs: newList){
    if(RateCardMap.containsKey(Jobs.Account__c+Jobs.Type__c)){
    Jobs.Hourly_Rate__c = RateCardMap.get(Jobs.Account__c + Jobs.Type__c).Hourly_Rate__c;
    }
    }
    } catch (Exception ex) { errMsg = ex.getMessage(); }
    return errMsg;
    }
    }

    Hope it may help you:

  • Parul

    Member
    September 18, 2018 at 7:27 am

    HI,

    Advantages of trigger Handler are:

    Facilitates logic-less triggers and One Trigger Per Object, which itself has many benefits(including fine grained control over order of execution)
    improves readability and Separation of Concerns(this improved readability makes version control more fruitful as well)
    optionally facilitates selective disablement.

     

    Thanks

  • shariq

    Member
    September 21, 2018 at 12:32 am

    Hi,

    Creating handler will give developer a better understanding of the code, it is the best practice, and you can also use this class at multiple places.

    Hope this helps.

Viewing 1 - 4 of 4 posts

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos