Concepts


Apex Helper Class


An apex helper class is a regular apex class designed to encapsulate logic so that it can be reusable therefore you might be able to execute that code from different places if possible.

Consider the following code logic to change the name of the account every time new accounts are inserted, we will intentionally place in an apex trigger so it looks like this:


trigger AccountNameChanger on Account (before insert, after insert, after delete) {
    if (Trigger.isInsert) {
        if (Trigger.isBefore) {
            for(Account acc : trigger.new){
                acc.Name = acc.Name + '1.0';
            }
        }
    }
}
  

As this logic is inside an apex trigger, specifically for account objects, if we want to use the exact same logic in an opportunity trigger we will definetly have to duplicate the code.

But having an apex helper class we could try to put a generic logic so that it can be reused not only in account but also in the opportunity trigger.

Now consider the following class which should perform the same :


public class NameChangerHelper {
    public static void ChangeName(List newObjects, boolean isBefore, boolean isInsert){
        if(isInsert && isBefore){
            for(SObject o : newObjects){
                string name = (string)o.get('Name');
                o.put('Name',name + '1.0');
            }
        }
    }
}
  

With the previous apex helper class NameChangerHelper now we can reuse its logic in the account trigger:


trigger AccountNameChanger on Account (before insert, after insert, after delete) {
    NameChangerHelper.ChangeName(trigger.new, trigger.isBefore, trigger.isInsert);
}
  

Or even in the an opportunity trigger:


trigger OpportunityTrigger on Opportunity (before insert, after insert, after delete) {
    NameChangerHelper.ChangeName(trigger.new, trigger.isBefore, trigger.isInsert);
}