1

What is the difference the methods used below in updating a list of records within an after update trigger context? The map variable just contains the opportunity ids that fired the trigger.

    List<ServiceAppointment> servicelst = [select id,Status,Opportunity__c from ServiceAppointment where Status != 'Completed' and Status != 'Canceled' and opportunity__c in :opptyupdatemap.keyset()];
    for(ServiceAppointment sa : servicelst) {
        sa.Status = 'Cancelled';
    }
    if(!servicelst.isEmpty()) {
        update servicelst;
    }

and this approach:

    List<ServiceAppointment> recordsToUpdate = new List<ServiceAppointment>();
    List<ServiceAppointment> servicelst = [select id,Status,Opportunity__c from ServiceAppointment where Status != 'Completed' and Status != 'Canceled' and opportunity__c in :opptyupdatemap.keyset()];
    for(ServiceAppointment sa : servicelst) {
        sa.Status = 'Cancelled';
        recordsToUpdate.add(sa)
    }
    if(!recordsToUpdate.isEmpty()) {
        update recordsToUpdate;
    }  

The second approach creates a new list to store the updated record values where the first approach just updates the existing list record values that were changed in the loop without adding those updated records to a new list. I'm interested in understanding the difference between both patterns. I always create a new instance of a list to add updated record field values. I'm getting reports that the code is not always working and the Service Appointment records status value is not getting correctly updated. I'm wondering if it is possible the cause would be because the code uses the instance of the first list?

| improve this question | | | | |
2

There is no real difference, adding a second collection just adds clutter. The use case where a second collection does help you is when you want to filter out only records you need to update. If you have a condition, you can reduce the number of query rows you operate on.

List<SObject> recordsToUpdate = new List<SObject>();
for (MyObject record : [/*query*/])
{
    if (/*condition*/)
    {
        /*field update*/
        recordsToUpdate.add(record);
    }
}
update recordsToUpdate;

Please note also that there is no need to check .isEmpty(). Performing DML Operations on an empty list does not consume any governor limits.

| improve this answer | | | | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.