Search code examples
salesforceapex-codeapex

Am I interpreting this Apex code correctly?


I have two Apex methods that accomplish the same thing. I am new to the framework and just want to make sure I am interpreting it correctly.

//Method 1: 
for (Account a : trigger.new) { 
  for (Contact c : [SELECT Id, OtherPhone FROM Contact WHERE AccountId= :a.Id]) { 
     c.OtherPhone= a.Phone; update c; } } 

//Method 2: 
for (Account a :trigger.new){ 
  acctMap.put(a.Id, a); 
}

for (Contact c : [SELECT Id, OtherPhone, AccountId FROM Contact WHERE 
AccountIdIN :acctMap.keySet()]){ 
  c.OtherPhone = acctMap.get(c.AccountId).Phone; 
  contactsToUpdate.add(c); 
} 
update contactsToUpdate;

My assumption is that both methods look at every Account being triggered, and append the account phone number to each Contact.OtherPhone variable under each account. Method 1 does this with an individual update to every contact and method 2 updates all affected contacts at once by pushing them into a hashmap.

Is this essentially correct? Clarification of anything I'm getting wrong would be much appreciated. Thanks!


Solution

  • You are basically right, both are doing pretty much the same thing, but I would not use neither.

    Long story short, Method 1 is not bulky, Method 2 is.

    For more details I'd say that

    • In method 1 there are some possible issues (depending also on the rest of the code)

      1. It is likely to hit the +100 SOQL Query Governor limit, as one SOQL Query is being done per each Account
      2. It is likely to hit the +150 DML statements
    • In method 2 there are also some small issues

      1. It is going through all the elements to create a map from the trigger.new, but trigger.newMap already has the map, so its processing power wasted, unless you want to compare the oldMap with the newMap to prevent unnecessary updates.
      2. contactsToUpdate is not declared anywhere :P
    • Both are fetching in the query OtherPhone, but OtherPhone is going to be overridden, so unless you want to do some other logic with it, there is no need to fetch it in the soql query (If the code in the org is complicated, every byte saved from the heap-size helps).

    Either way, this functionality can even be accomplished without code using process builder ;)

    I hope its helpful.