Important Salesforce Apex Triggers Best Practices1) Write One Trigger per one Object
You can have n number of triggers on single object, but as apex best practice we should write logic in handler class. If you write multiple Triggers on single object, we cant control order of execution .
2) Always write Logic-less Triggers
Always write logic in apex handler or helper 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 and DML statements inside FOR Loops
This is one of the salesforce apex best practices. Since apex is running under Multi-tenant architecture it strictly enforces some governor limits to control wastage of resource utilization. if we use soql inside for loop, that may causes to hit governor 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. As a good developer you should learn effective usage of Map.
6)Avoid to 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 with proper filter conditions(Where conditions) , 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 Hard-coding IDs
Don't hard code IDs into queries or apex code. Rather query on some other data to retrieve the desired rows. Record Id's can change across org's.
9) Handle recursion
As triggers gets invoked automatically when dml occurs, there could be scenarios where same trigger logic gets called multiple times. This may cause unnecessary resource consumption (Query, cpu time, dml). So we need to handle such code of scenarios effectively.