function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ethan huntethan hunt 

Avoid instantiating new objects inside loops

Hi,

I am getting the following rule exception on the below line of code. Please suggest what can be the alternative for this -

Opportunity updateOpportunity;
        List<Opportunity> listToUpdateMasterOpportunity = new List<Opportunity>();
        for(Opportunity opp : updateMasterOpportunity) {
            updateOpportunity = new Opportunity(id = opp.id); ////////////Avoid instantiating new objects inside loops
            if(mapCalculatedMasterOptyVal.get(opp.id) != null) {
                updateOpportunity.Sub_Opportunities_Total_Amounts__c = mapCalculatedMasterOptyVal.get(opp.id);
            }
            listToUpdateMasterOpportunity.add(updateOpportunity);
        }
        opportunityDao.updateOpportunity(listToUpdateMasterOpportunity);
    }
Gonzalo AbrunaGonzalo Abruna
I'd use a different approach, adding opp to the list, not updateOpportunity:

List<Opportunity> listToUpdateMasterOpportunity = new List<Opportunity>();

        for(Opportunity opp : updateMasterOpportunity) {
            
            if(mapCalculatedMasterOptyVal.get(opp.id) != null) {
                opp.Sub_Opportunities_Total_Amounts__c = mapCalculatedMasterOptyVal.get(opp.id);
            }
            listToUpdateMasterOpportunity.add(opp);
        }
        opportunityDao.updateOpportunity(listToUpdateMasterOpportunity);
    }