triggerssalesforcetest-classapex-trigger

Need optimization of this trigger?Can anyone help me out.?


Actually, I am trying to get Area_c field from custom object(Zip Codes) into the lead object custom field Area_c. So, I have written some of the code but is there any other way to write it or get some optimization of this code.

trigger OpportunityPriceBook on Lead (before insert) { 

List<String> zipList = new List<String>();

for(Lead lead : Trigger.new){

   zipList.add(lead.PostalCode);

}

List<Zip_Code__c> zipCodeList = [Select Id, Name, City__c, Area__c from 

Zip_Code__c WHERE Name IN : zipList];

for(Lead leads : Trigger.new){

    for(Integer i =0 ; i < zipCodeList.size(); i++)
      {
         leads.Area__c = zipCodeList.get(i).Area__c;
         leads.City = zipCodeList.get(i).City__c;
         break;
      }   

    }

  }

Solution

  • Given the code, there are a couple of ways that you can simplify your last multi-dimensional for loops; nested for loops can be problematic at times due to their exponential nature.

    That point made, you have one pretty glaring bug in your code: You do not have an identifying conditional statement in your nested for loop, and actually always only set the lead to the first zipcode's data each time.

    This is the approach I would take:

    // Extract out the postal codes of the leads
    List<String> zipList = new List<String>();
    for (Lead lead : Trigger.new) {
        zipList.add(lead.PostalCode);
    }
    
    // Query for the related Zip Codes, and map them by Name
    List<Zip_Code__c> zipCodeList = [SELECT Id, Name, City__c, Area__c FROM Zip_Code__c WHERE Name IN :zipList];
    Map<String, Zip_Code__c> zipCodeByName = new Map<String, Zip_Code__c>();
    for (Zip_Code__c zipCode : zipCodeList) {
        zipCodeByName.put(zipCode.Name, zipCode);
    }
    
    // Stamp leads with the Area and City as identified by the matching Zip Code
    for (Lead lead : Trigger.new) {
        Zip_Code__c zipCode = zipCodeByName.get(lead.PostalCode);
        lead.Area__c = zipCode.Area__c;
        lead.City = zipCode.City__c;
    }