For one of the requirements I have to write code to update multiple records of different objects. Originally I was planning to do the obvious: get needed records, change some value, update these lists, but then I though... Why don't I just use a list of generic SObject?
Then I tried to find some pros and cons of using List<SObject>
vs. multiple lists per object type and I could only find one:
- Only 1
update
needed for all records(= less DML operations)
Example code:
List<Opportunity> opps = [SELECT Id, OwnerId, Name FROM Opportunity WHERE Name LIKE :nameString AND OwnerId IN :fromUsers];
List<Lead> leads = [SELECT Id, OwnerId, Name FROM Lead WHERE Name LIKE :nameString AND OwnerId IN :fromUsers];
List<SomeCustomObject__c> objs = [SELECT Id, OwnerId, Name FROM SomeCustomObject__c WHERE Name LIKE :nameString AND OwnerId IN :fromUsers];
// do something with these lists, based on the requirements
update opps;
update leads;
update objs;
But this will require 3 DML operations(+any other triggered by triggers/processes/workflows). But we could simply replace the 3 DML operations by the following:
List<SObject> allRecordsToUpdate = new List<SObject>();
allRecordsToUpdate.addAll((List<SObject>)opps);
allRecordsToUpdate.addAll((List<SObject>)leads);
allRecordsToUpdate.addAll((List<SObject>)objs);
update allRecordsToUpdate;
I know, that in this case we only save 2 DML operations, but once we will need to update 10, 20, 30, whatever... different objects it might be a lifesaver.
So the question is: what are the pros and cons of using List<SObject>
?