Best Practice #1: Bulkify your Code
Here is an example of poorly written code that only handles one record:
trigger accountTestTrggr on Account (before insert, before update) {
//This only handles the first record in the Trigger.new collection
//But if more than one Account initiated this trigger, those additional records
//will not be processed
Account acct = Trigger.new[0];
List contacts = [select id, salutation, firstname, lastname, email
from Contact where accountId = :acct.Id];
}
The issue is that only one Account record is handled because the code explicitly accesses only the first record in the Trigger.new collection by using the syntax Trigger.new[0]. Instead, the trigger should properly handle the entire collection of Accounts in the Trigger.new collection.
Here is a sample of how to handle all incoming records:
trigger accountTestTrggr on Account (before insert, before update) {
List<String> accountNames = new List<String>{};
//Loop through all records in the Trigger.new collection
for(Account a: Trigger.new){
//Concatenate the Name and billingState into the Description field
a.Description = a.Name + ':' + a.BillingState
}
}
Notice how this revised version of the code iterates across the entire Trigger.new collection with a for loop. Now if this trigger is invoked with a single Account or up to 200 Accounts, all records are properly processed.