function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JoyDJoyD 

When to move code into a Class from a Trigger?

I was just curious at what point of developing your Trigger, do you decide to move your code to a Class instead?  My Trigger keeps getting larger, but because I need to iterate through the Trigger.new, I haven't wanted to move everything out to a Class - but now I'm wondering if it would make life easier (though harder at first...)?

Best Answer chosen by Admin (Salesforce Developers) 
Ken_KoellnerKen_Koellner

I put the entire business logic in a class.  The trigger code is never more than two or three lines.  It may inspect the flags such as isUpdate, isInsert, etc. then it calls the method in the class.  It passes in the new/old old lists/map as needed.  The way the class, at least in theory, could also be used outside the context of a trigger.  The class does not refence any of the Trigger items directly.

 

 

All Answers

Ken_KoellnerKen_Koellner

I put the entire business logic in a class.  The trigger code is never more than two or three lines.  It may inspect the flags such as isUpdate, isInsert, etc. then it calls the method in the class.  It passes in the new/old old lists/map as needed.  The way the class, at least in theory, could also be used outside the context of a trigger.  The class does not refence any of the Trigger items directly.

 

 

This was selected as the best answer
BritishBoyinDCBritishBoyinDC

I found this a very useful post when I was trying to get better at designing triggers/classes

 

http://gokubi.com/archives/two-interesting-ways-to-architect-apex-triggers

JoyDJoyD

Thank you both, that's helpful.  Thought I could mark you both as solutions, oh well sorry...  :-)

skodisanaskodisana

Hi,

 

As a best practice we need to use Apex classes. Because code redundancy will not happen.

You can call the same classes (Business logic)  from different places like Triggers, Apex Class, Visualforce pages.

In trigger you can stop the Recursive calling since we cannot declare Static variables.

So always better to use classes is best option.

 

Thanks,

Kodisana