1
votes

Account and Contact both have Billing_Address__c field. Contact also have checkbox called active__c. If active__c is true and Account Billing_Address__c is update, then Contact's Billing_Address__c is updated . Here is the trigger. It is working fine. But I want to know if there is any problem or how can I optimize this in the terms of memory?

 public static void updateContactBillingAddress(List<Account> lstNew, Map<Id,Account> mapOld){
    Set<Id> accIds = new Set<Id>();
    for(Account acc : lstNew){
        if(acc.Billing_Address__c != mapOld.get(acc.Id).Billing_Address__c && acc.Billing_Address__c !=null){
            accIds.add(acc.Id);
        }
    }
    if(!accIds.isEmpty()){
        List<Contact> lstContact = new List<Contact>([Select ID,active__c, Account.Billing_Address__c,Billing_Address__c FROM Contact where AccountID IN :accIds]);
        List<Contact> lstUpdateCon = new List<Contact>();
        for(Contact con : lstContact){
            if(con.active__c == true){
                if(con.Billing_Address__c != con.Account.Billing_Address__c){
                    con.Billing_Address__c = con.Account.Billing_Address__c;
                    lstUpdateCon.add(con); 
                  }
             }
            else{
                con.Billing_Address__c =null;
                lstUpdateCon.add(con); 
            }
        }
        if(!lstUpdateCon.isEmpty()){
            update lstUpdateCon;
        }
    }
}
1

1 Answers

1
votes

Not really, it's semantics but i'd return a contact, 1 method, 1 thing. You're processing accounts and updating them, I'd return the List of contacts and not update them in the same method. If you need to update contacts down the road you will end up doing unnecessary DML statements, you also don't need to create a List just for that loop.

public static List<Contact> updateContactBillingAddress(List<Account> lstNew, Map<ID,Account> mapOld)
{
    List<Contact> result = new List<Contact>();

    Set<Id> accIds = new Set<Id>();

    for(Account acc : lstNew)
    {
        if(acc.Billing_Address__c != null && acc.Billing_Address__c != mapOld.get(acc.Id).Billing_Address__c)
        {
            accIds.add(acc.Id);
        }
    }

    if(!accIds.isEmpty())
    {        
        for(Contact con : [Select ID,Active__c, Account.Billing_Address__c,Billing_Address__c FROM Contact where AccountID IN :accIds])
        {
            if(con.Active__c == true){
                if(con.Billing_Address__c != con.Account.Billing_Address__c)
                {
                    con.Billing_Address__c = con.Account.Billing_Address__c;
                    result.add(con); 
                }
             }
            else
            {
                con.Billing_Address__c = null;
                result.add(con); 
            }
        }
    }

    return result;
}