Count number of contacts on accounts using Trigger following best practices

In the below example I have followed best practices to write logic for counting number of contacts on account object.

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);
        
    }
}
 Countcontact

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());
        }
    } 
}

I hope you enjoyed this article. For more of these kind of articles stay tuned. Happy Coding !

Reference:

Trigger Class

Trigger Syntax

Trigger Exceptions

Trigger Context Variable

Common Bulk Trigger Idioms

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