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
mxalix258mxalix258 

understanding filtering in apex code

If I have a trigger, is there any benefit to only passing the records that I want to be processed? For example, if i want a trigger list to be passed to an apex class....should I filter the selected records inititally in the trigger? In the case shown below, when it gets to the "trigger.new" does it pass ALL the records that are in the list? or only the ones that fit the criteria of objectc.field='x'?

 

ApexClass ac = new ApexClass ();

if (objectc.field = 'x'){
ac.acMethod(Trigger.new);

}

SidharthSidharth

by Trigger.new it will pass/process all the records .

it depends what your class is doing, and what records you want to pass/process in the class

 

but for filtering use can use :

 

for(Object obj: Trigger.new){

  it will iterate over each record in Trigger.new for that trigger object

  filter them here, and store them in a separate list, and than process this list

}

sfdcfoxsfdcfox

Trigger.new is a list, so yes, it would pass in up to 200 records. Pre-filtering the list into a separate list may reduce your class' script execution by n * class-statements, where n is the number of records pre-filtered. It may also reduce the number of query rows returned, etc. You could also filter inside the class. If the class is commonly called from several places, filtering inside the class reduces the amount of code required overall. Here's how filtering in a trigger should look like:

 

trigger X on Y (Z) {
  SObject[] matched = new SObject[0];
  for(SObject A:Trigger.new) {
    if(a.field__c=='x') {
      matched.add(a);
    }
  }
  ApexClass ac = new ApexClass();
  ac.acMethod(matched);
}

Replace A, X, Y, Z, SObject, Field__c, ApexClass with the appropriate values.

 

You can use this same design pattern in the class to reduce the trigger complexity to just two lines of code (or 1, if its a static method), assuming the filtering logic is identical in all cases. If not, then a trigger like this would work just fine.