Decoupling Salesforce Trigger Automation

Ben Butler
2 min readAug 19, 2021

--

Unlocked packages are the future. The problem is designing systems that are not monolithic and tangled. Unfortunately that is the default and untangling is the exception hack.

To do this decisions need to be made dynamically at runtime. This is how to do it using both Apex and Flows.

The Shared Unlocked Package Dependency

Create a custom metadata type. This is used to allow dynamic calling of apex classes.

Create a flow trigger interface

public interface ITriggerFlow {
void run();
}

Create the object trigger. With these alone we have enabled ourselves

  • Separation of concerns
  • Complete decoupling
  • Trigger toggles
public class ObjectTriggerHandler {
public static void runTriggers(){
for (RecordBasedFlow__mdt flow : [SELECT ApexClass__c FROM RecordBasedFlow__mdt WHERE Object__c = 'Opportunity' ORDER BY Order__c]){
ITriggerFlow flowClass = (ITriggerFlow)Type.forName(flow.ApexClass__c).newInstance();
flowClass.run();
}
}
}

The Licensing Unlocked Package

Merely add the new custom metadata record to the shared dependency for Licensing.

public class LicensingFlow implements ITriggerFlow {
public void run(){
Flow.Interview f = new Flow.Interview.Create_Licenses(new Map<String, Object>());
f.start();
}
}

The Pricing Unlocked Package

Again, add the new custom metadata record to the shared dependency for Pricing.

public class PricingFlow implements ITriggerFlow {
public void run(){
Flow.Interview f = new Flow.Interview.Calculate_Pricing(new Map<String, Object>());
f.start();
}
}

Notes

This whole thing is carried by the “Type” class. Type allows us to convert strings to Apex classes, which makes it essential for all triggers. Since Apex classes can do many other things, invoking flows among other things, this allows us to decouple almost every action.

We can uninstall a package with ease, with mere configuration changes. We can modularize our systems and treat them as plugins. We are now free.

Except the team has to actually do it, of course.

Patterns: Dependency Injection,

--

--

No responses yet