What is an Execution Context in Salesforce?
While Reading the book Advanced Apex Programming by Dan Appleman, I found this very interesting topic that I thought I might share with you.
If you are a Salesforce Developer you must’ve heard the term “Execution Context”. I think a Salesforce Developer should know exactly what that term means because it influences every aspect of development of the Salesforce Platform.
What is an Execution Context?
In simple words, this context represents the time between when the code is executed and when it ends. To understand this term in more depth check the below example.
Do you remember Triggers? If you do, Consider a scenario where you have a Before Insert trigger on your Account object. In this case the execution context starts when you insert an Account and ends when the trigger code exists as shown below.
Now let’s assume a more complex scenario where you have multiple triggers on the Account object, A before insert trigger and an after insert trigger. This is how the execution context would look like.
Notice that both triggers run in the same execution context. Which means they share the same set of limits and static variables. Now let’s assume that I created a validation rule on the Account object, that’s how the execution context would look like.
Why do I have to know the Execution Context?
There are two reasons for why you should:
Static variables: A static variable’s value is the same throughout the execution context, and are unique to an execution context.
Governor Limits: Limits are reset between execution contexts.
As you saw in the example above, the code that runs in the same execution context share the same limits and static variables. For example when dealing with the total number of DML statements that can be issued, this number is not specific to the before insert trigger only, it also includes the after insert trigger. Which means that the total number of DML statements in (after insert + before insert) must not exceed 150 statements. This goes for other limits too like SOQL and SOSL queries.
What starts an Execution Context?
Any of the following events can start an execution context:
- Asynchronous Calls (Batch Apex, Future method, Queuable Apex,Scheduled Apex)
- Web Service
- Visualforce and Lightning Components
- Processes, Flows and Workflows
- Anonymous Apex (ex. Code executed on the Developer Console)
To know more about execution contexts and the order of execution, check the below resources:
Happy Learning :)!