1) Write One Trigger per one Object
You can have n number of triggers on single object, but as apex best practice we have to write event operations into the singe trigger with the if conditions. Example code like below
A single Apex Trigger is all you need for one particular object. If you write multiple Triggers on single object, we may don’t know which one will be works first.
2) Always write Logic-less Triggers
Always write logic in apex class so that we can reuse it. Create context-specific handler methods in Trigger handler class
3) Always Bulkify your Code
your code must work on more than one record at a time.
Bulkifying Apex code means we make sure the code properly handles more than one record at a time. The trigger code must be process on multiple records instead of single record for avoid hitting governor limits.
4) Always Avoid SOQL Queries or DML statements inside FOR Loops
Since apex is running under Multitenent architecture it stricly enforces some time limits. if we use soql inside forloop, that may causes to hit governer Limits.
If we write SOQL query inside for loop that iterates across all object records. Soql query will be executed for each record. An individual Apex request works 100 SOQL queries before exceeding that governor limit. So if the trigger is invoked by a batch of more than 100 records, the governor limit will throw a runtime exception.
Total number of SOQL queries issued for a single Apex transaction- 100
Total number of DML statements issued-150
5) Using Collections, Streamlining Queries, and Efficient For Loops to avoid governors.
It is important to use Apex Collections(LIST, SET,MAP) to efficiently query data and store the data in memory.
6) Query Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then Use SOQL in For loop, to avoid 50001 limit error.
7) Use @future Appropriately
@Future is used to run processes in a separate thread, at a later time when system resources become available. @Future have Future methods that will runs asynchronously.
8) Avoid Hardcoding IDs
Don’t hardcode IDs into queries or apex code. Rather query on some other data to retrieve the desired rows.
Motivation for Advice
Record IDs can change – for example between a sandbox and a production environment. If code is not written properly, this will result in faulty code.