Roll up Summary Trigger following best practices

In the below example I have followed best practices to write logic for counting number of contacts on account object. Please understand carefully as it is very common question in interviews.

I have applied following points:

  1. Logic less trigger by using helper class
  2. Handled exception using try, catch
  3. Handled null point exception by putting null check

rollupOnContact.apxt

trigger rollupOnContact on Contact (after insert, after update, after delete, after undelete) {
    
    if(Trigger.isinsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
       
        Countcontact.Countcontacts(trigger.new,trigger.old);
        
    }
}

Countcontacts.apxc

public class Countcontact {
    public static void countcontacts(List<contact> newcontact,List<contact> oldcontact){
     
        set<id> accids= new set<id>();
                try{
        if(newcontact !=null){
            for(Contact c:newcontact){
                if(c.AccountId!=null){
                accids.add(c.accountid);
                }
            }      
       }if(oldcontact!=null){
            for(Contact c:oldcontact){
                accids.add(c.accountid);
            }
       }
     List<Account> acc = [Select id, NoofContacts__c,(Select id from Contacts) from Account where id IN: accids];
        if(acc!=null){
        for(Account accValue:acc){
            accValue.NoofContacts__c = accValue.Contacts.size();
        } 
        }
        if(!acc.isempty()){
        update acc;
        }
        }
        catch(exception e){
            System.debug('Get Message'+e.getMessage());
        }
    } 
}

 

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes

1 comment on “Roll up Summary Trigger following best practices

  1. mahesh jadhavar

    cont no of contact on acc

    Account A -> 2 con
    no of contact = 2
    Account B -> 1 con ,
    Account B is parent of A
    no of contact => 3
    Account C -> 2 con ,
    C is parent of B
    no of contact => 5

    how to achieve this requirement

Comments are closed.