1

I know a trigger best practice would not include logic within the trigger itself and this should be put in a separate class which is fine.

However, if you have multiple operations being performed by a trigger for different business cases, would you usually store all of this in the same class or would you have separate classes to handle each business case and then call each class from the same trigger (one after another)... i.e:

myHandler obj = new myHandler ();
obj.handleBeforeUpdate(Trigger.NewMap);

myHandler2 secondObj = new myHandler2 ();
secondObj.handleBeforeUpdate(Trigger.NewMap);

Thanks

1 Answer 1

7

For my org, I break up the logic for each trigger into multiple classes.

For example, my org's Account trigger has classes for:

  • Propagating the owner from Parent Accounts to their children
  • Rolling up financial data from Child Accounts to their Parents
  • Managing the status of Child (and Parent) Accounts based on the number of services the Account is being billed for
  • ...and a few other things

Doing so allows you to have each class focus on performing one task (or maybe two), which makes unit testing very simple.

Writing tests, especially the setup for each test, was a major pain point before I transitioned my org to this structure (trigger framework + tightly-scoped classes to be run in triggers). Not only would I need to perform the setup required for the thing I was testing, but I would need to make sure that all of the code that ran before the part of the monolithic class that I was testing would not cause a failure that would end the test before I got to the code I wanted to test in the first place.

A few downsides to this approach are:

  • It's no longer as obvious which classes are being used in the trigger, nor the order they're executed in. In most cases, I'd think you'd need to look in the handler for the trigger to determine what is being called (and in what order)
  • While you gain ease of testing individual parts of the code executed by your trigger, you lose the inherent "integration tests" (testing how your code interacts with other pieces of code) that you get when testing a monolithic class. You can still do integration testing, but it needs to be done explicitly

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .