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
daniel.knecht1.396874461719167E12daniel.knecht1.396874461719167E12 

Question on efficiency of class

Hi everyone,

I am currently working on a trigger to fire on insert or update and maintain the number of records with the same name in the respective field on all records with the same name. As I have been confronted with a "Too many SOQL" error, I have continuously tried to improve the efficiency of my trigger/class up to a point, where I cannot believe that the failed Tests are actually linked to this particular piece of code.

Question 1) Do you see anything which I should not do in the below code?
Question 2) Could the below code be part of a recursive trigger-merry-go-round? Would it be an option to check for trigger.old vs. trigger.new comparison on the fields in question? (if no change happened, do nothing)

I am pasting just the most important snippet of the code, as the rest is just part of trigger handling.
 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Count number of contacts with same name for duplicate check
      
private static void IdenticalContacts(List<Contact> newContacts){

if(updatingContacts) { return; }
if(checkRecursive2.runOnce()){ 

String IPNames = [SELECT Name FROM Contact WHERE ID in :newContacts].Name;
Integer I = [select count() from Contact where Name = :IPNames]; 
List<Contact> AllIPs = new List <Contact>([SELECT ID, Number_of_contacts_with_same_name__c, Name FROM Contact WHERE Name = :IPNames]);
  
for (Contact b :AllIPs){

 //Sets number of counted records in existing and new records
 b.Number_of_contacts_with_same_name__c = i;
 }

updatingContacts = true;
update AllIPs;
updatingContacts = false;
}
}


 
Deepak Kumar ShyoranDeepak Kumar Shyoran
From the above code it doest seems something wrong with the above code. As you are not firing any SOQL inside a loop. I not sure as this code updates contact which might trigger this to fire repeatedly this is something you need to check if so then you need to use a static variable and set the first time when this class execute and check that for the next time to stop this trigger from firing again. 
Roy LuoRoy Luo
Try this:

//List<Contact> newContacts= [SELECT Id FROM Contact LIMIT 10];
Set<Id> newContactIds  = new Map<Id, Contact>(newContacts).keySet();
AggregateResult[] groupedResults
  = [SELECT Name, COUNT(Id) nameCount FROM Contact WHERE Id IN :newContactIds GROUP BY Name];
Map<String,Integer> nameCountMap = new Map<String, Integer>();
for(AggregateResult r: groupedResults)
{
  nameCountMap.put(String.valueOf(r.get('Name')), (Integer)r.get('nameCount'));    
}