December 3, 2016 by LanceShi
3.3 Considerations of writing triggers and some best practice
Before we proceed to the next example, there are a few concepts and considerations we need to go through for the triggers.
In Apex, every trigger is a bulk trigger. Which means there can be up to 200 elements in trigger.new list. Always keep that in mind and always think about bulkification when you write your trigger code.
Trigger context variables
We have a bunch of trigger context variables for us to use. Trigger.new is just an example of them.
The most frequent used ones can be categorised into three groups:
- Trigger.New, Trigger.Old, Trigger.NewMap, Trigger.OldMap. Those four context variables are containers of the SObject records. New means the records with updated value. Old means previous records with previous values. Map means an Map<Id, SObject> map from the SObject Id to the record itself.
- Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete. Those four boolean variables tells whether the current trigger is an insert/update/delete/undelete trigger.
- Trigger.isBefore, Trigger.isAfter. Tells whether it is a before trigger or after trigger.
Context variable considerations
The full list of considerations are here.
What you especially need to pay attention to is:
- You can’t directly do DML to Trigger.New.
- Trigger.Old is always read only
- Trigger.New is readonly in after trigger.
One trigger for each SObject
You can have multiple triggers for one SObject. But it is never recommended. The execution sequence of those triggers are random so it will be disastrous.