Apex Triggers
Before we go for best practices let’s know some basic about apex trigger. Apex can be invoked by using triggers. Apex triggers enable you to perform custom actions before or after changes to Salesforce records, such as insertions, updates, or deletions.
A trigger is Apex code that executes before or after the following types of operations:
insert
update
delete
merge
upsert
undelete
For example, you can have a trigger run before an object’s records are inserted into the database, after records have been deleted, or even after a record is restored from the Recycle Bin.
There are two types of triggers:
Before triggers are used to update or validate record values before they’re saved to the database.
After triggers are used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field) and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue. The records that fire the after the trigger is read-only.
1 – Logic-less trigger – All trigger must be logic-less means all the code should be in a separate apex class knows as handler class.
2 – Bulkify your Trigger – Make sure that your trigger will not cause any issue while importing mass records.
3 – Avoid hardcoding Ids – Do not use hard code ids anywhere in Class or Trigger.
4 – Avoid SOQL queries and DML inside for loops so that governor limit cannot be hit.
5 – Use Collection List, and Map to avoid DML and SOQL inside for Loop.
6 – Bulkify your helper class methods!
7 – Do not develop multiple triggers on the same object. Creating, one trigger every object will let you decide in which order what code need to execute.
8 – Always query large data set with the maximum possible filter to avoid the governor limit.
9 – Use @future Appropriately
10 – Use of the Limits Apex Methods to Avoid Hitting Governor Limits
11 – Use Apex Trigger framework.
12 – Use utility class where is required and possible
Trigger Frameworks and Apex Trigger Best Practices