1

How can I optimise this code ?its work though

public class TaskTriggerHandler{
     public void BeforeInsert(List<SObject> triggerNew) {}

    public void BeforeUpdate(List<SObject> triggerNew, Map<Id, SObject> triggerOldMap) {}

    public void BeforeDelete(List<SObject> triggerOld) {}

    public void AfterInsert(List<Task> triggerNew) {
        UpdateContactOnInsertTask(triggerNew);
    }

    public void AfterUpdate(List<Task> triggerNew, Map<Id,SObject> triggerOldMap) {
        UpdateContactOnInsertTask(triggerNew);
    }

    public void AfterDelete(List<Task> triggerOld) {
        UpdateContactOnInsertTask(triggerOld);
    }

    public void AfterUndelete(List<SObject> triggerNew) {}

    //Methods
    public void UpdateContactOnInsertTask(List<Task> triggerNew){

        List<Contact> listOfContactClosed = new List<Contact>();
         Set<id> setofClosedTask = new Set<id>();
          Set<id> setofOpenTask = new Set<id>();
        Set<id> setofContactIds = new Set<id>();
        for(Task objTask :triggerNew){
            if(string.valueOf(objTask.WhoId).startsWith('003')){
                setofContactIds.add(objTask.WhoId);
            }
        }
        if(setofContactIds.size()>0){
            for(Contact objContact :[Select id,OpenTask__c,ClosedTask__c,(Select id,isClosed from Tasks ) from Contact where id in:setofContactIds]){
                for(Task objTask :objContact.Tasks){
                    if(!objTask.isClosed){
                        setofOpenTask.add(objTask.id);
                    }
                    else{
                        setofClosedTask.add(objTask.id);
                    }
                }

                listOfContactClosed.add(new Contact(id=objContact.id,OpenTask__c=setofOpenTask.size(),ClosedTask__c=setofClosedTask.size()));
            }
            Update listOfContactClosed;
        }
    }
}
  • Code is working and fine – Raju Sen Jan 5 '17 at 13:39
  • 2
    why isn't setofOpenTask and setofClosedTask cleared for every Contact fetched in the SOQL? – cropredy Jan 5 '17 at 20:24
  • 2
    use objTask.WhoId.getSobjectType() == Contact.SObjectType as best practice – cropredy Jan 5 '17 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.