A static variable retains it`s value throughout an execution context. An execution context is invoked from a button click, web service call, a trigger etc.
One of the many ways a static variable can be used is to flag when a trigger has already fired and what to do with a re-entrant trigger.
Suppose you had the following class:
public class p {
public static boolean firstRun = true;
}
A trigger that uses this class could then selectively fail the first run of the trigger:
trigger t1 on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}
If the static variable was set in the trigger like this:
trigger t1 on Account (before delete, after delete, after undelete) {
static boolean firstRun = true;
if(Trigger.isBefore){
if(Trigger.isDelete){
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}
When the trigger might fire again on the same object, even if you set it to false in the next trigger context it will still be set to true and code will execute something that was not planned.
From what I found the Apex runtime engine considers, an operation of a trigger, a single unit of work so it might be that when the second time a trigger executes the engine focuses on the particular trigger and not the previous one. So by putting the static variable in a class, it`s life is governed by the whole execution context which might be composed of many actions and not the trigger execution context.
UPDATE
I've been reading about static variables in trigger and there are a couple of reasons why you should not use them:
- It is bad practice to write logic inside your trigger, minimizing the amount of code in a trigger and instead implement all functionality in class.
- Having static variables separated in a class will help you with the unit test by loading up the static variables with the required data and not rely on the fact that you have to trigger the trigger in order to populate with test data test your scenario.
- Also the most important thing to know about triggers is that when you have more than one trigger of the same type, you cannot predict the order in which they will fire. So if you have a static variable in a trigger that has a value that another trigger will depend on than you would have some problems.
Hope it helps, if you think some code will help you to understand better, let me know.