Organizing triggers with Salesforce DX?

I’m in the process of breaking up our org into smaller, logical projects to fit in with the Salesforce DX paradigm, but something that I’m getting stuck on is triggers. Best practice is to have one trigger per object, have that trigger be logic-free and call a handler class, and have the handler class implement the logic in some fashion. We have triggers with logic that would span logical projects, though. In my specific case, I have two projects that require a trigger on User.

What is the best practice for handling multiple projects that require triggers on the same object?


One approach is trigger factory and dynamically invoking the apex handler classes.

Let’s say you have three projects:

  • common
  • app1
  • app2

The common project has the single apex trigger for the object, say AccountTrigger.cls. This trigger does not have business logic in itself but rather uses a factory design pattern to lookup from configuration a list of handler apex classes to invoke in order. The list of apex classes could be stored in custom metadata types. The CMDT would have two fields: apex class name (text) and run order (number).

The other two projects, app1 and app2, contain their apex handler classes but no trigger. They also could contain their CMDT record so when deployed hooks into the trigger factory (or the configuration of the CMDT could be handled outside the projects).

You could also organize and deploy these three projects as Developer Controlled Packages to express dependencies that app1 and app2 depend on common package.

Source : Link , Question Author : Mike Chale , Answer Author : Doug Ayers

Leave a Comment