Triggers

Putting logic into your triggers creates un-testable, difficult-to-maintain code.

Best-practice is to move trigger logic into a handler class. This pattern take it a step further moving each each action into an Operation class of it's own, improving separation of concerns and test ability.

Opportunity Trigger

trigger OpportunityTrigger on Opportunity (before insert, before update) {
    new OpportunityTriggerHandler().run();
}

Example Trigger Handler Example

Notice the Trigger__c custom setting, this is used to easily enable or disable the trigger.

public without sharing class OpportunityTriggerHandler extends TriggerHandler {

    public override void beforeUpdate() {

        if (isTriggerEnabled()) {
            new OpportunityActionOperation(Trigger.oldMap, Trigger.newMap).execute();
        }
    }

    private Boolean isTriggerEnabled() {
        return Triggers__c.getOrgDefaults().Opportunity_Trigger__c;
    }
}

Here are all of the methods that you can override. All of the context possibilities are supported.

  • beforeInsert()

  • beforeUpdate()

  • beforeDelete()

  • afterInsert()

  • afterUpdate()

  • afterDelete()

  • afterUndelete()

Opportunity Trigger Operation Example

Notice the Trigger__c custom settings, this is used to easily enable or disable this specific operation.

Trigger Handler base class

A minimal trigger framework for your Salesforce Apex Triggers by Kevin O'Hara

Last updated