Sunday 10 June 2012

Writing trigger - A Clean Approach

What is a best way to write a trigger? Different people will have different opinions and different answers for this question. Here is one clean approach to write a trigger which will be following below few guidelines:
1. There should be only one trigger on one object.
2. There  should be only one loop per event. For Ex: before Insert, before Update etc.

Here is the sample trigger code which implements above guidelines.

Trigger testObjectTrigger on TestObject__c(before Insert,before update, after insert, after update)
{
  List<TestObject__c> testObjectListBeforeInsert=new List<TestObject__c>();
  List<TestObject__c> testObjectListBeforeUpdate=new List<TestObject__c>();
  List<TestObject__c> testObjectListAfterInsert=new List<TestObject__c>();
  List<TestObject__c> testObjectListAfterUpdate=new List<TestObject__c>();

 
  if(Trigger.isBefore)
 {
    if(Trigger.isInsert)
   {
     for(TestObject__c toc: trigger.New)
     {
       Boolean isBeforeInsertCondition=<Your condition >;
       if(isBeforeInsertCondition)
       {
        testObjectListBeforeInsert.add(toc);
        }
     }   
    }
    if(Trigger.isUpdate)
    {
      for(TestObject__c toc: trigger.New)
     {
       Boolean isBeforeUpdateCondition=<Your condition >;
       if(isBeforeUpdateCondition)
       {
        testObjectListBeforeUpdate.add(toc);
        }
      }   
    }
 }
 if(Trigger.isAfter)
 {
   if(Trigger.isInsert)
   {
     for(TestObject__c toc: trigger.New)
     {
       Boolean isAfterInsertCondition=<Your condition >;
       if(isAfterInsertCondition)
       {
        testObjectListAfterInsert.add(toc);
        }
     }   
   }

  if(Trigger.isUpdate)
    {
      for(TestObject__c toc: trigger.New)
     {
       Boolean isAfterUpdateCondition=<Your condition >;
       if(isAfterUpdateCondition)
       {
        testObjectListAfterUpdate.add(toc);
        }
      }   
    }
 }
 if(testObjectListBeforeInsert.size()>0)
 {
   ............
   Your code to perform operation or call to other class method to perform operation.
   .............
 }
 if(testObjectListBeforeUpdate.size()>0)
 {
   ............
   Your code to perform operation or call to other class method to perform operation.
   .............
 }
 if(testObjectListAfterInsert.size()>0)
 {
   ............
   Your code to perform operation or call to other class method to perform operation.
   .............
 }
 if(testObjectListAfterUpdate.size()>0)
 {
   ............
   Your code to perform operation or call to other class method to perform operation.
   .............
 }

}
In above example i have only taken insert and update operation but above code can be extended to other operations also like delete,undelete etc.

No comments:

Post a Comment