Plat-Dev-201 practice question 25 of 30

A developer has an integer variable called maxAttempts. The developer needs to ensure that once maxAttempts is initialized, it preserves its value for the length of the Apex transaction; while being able to share the variable's state between trigger executions. How should the developer declare maxAttempts to meet these requirements?

Full set: 204 questions
Answer options
A: Declare maxattempts as a constant using the static and final keywords.
B: Declare maxattempts as a member variable on the trigger definition.
C: Declare maxattempts as a variable on a helper class.
D: Declare maxAttempts as a private static variable on a helper class. Correct answer
Correct Answer:
D. Declare maxAttempts as a private static variable on a helper class.
Explanation

Static variables in Apex are scoped to the entire transaction. Their value is initialized when the class is first loaded and persists across multiple trigger executions within that single transaction (e.g., if a workflow rule causes the trigger to fire again). Declaring maxAttempts as a private static variable in a helper class is the standard best practice. The static keyword ensures the state is preserved for the transaction's duration, while private enforces encapsulation. Using a helper class separates logic from the trigger body.

Why Incorrect

A. Using final makes the variable a constant that can only be assigned once, which may be too restrictive if its initial value is determined dynamically.
B. A member (instance) variable on the trigger definition is not shared across trigger executions, as a new instance may be created.
C. This is too generic. The variable must be static to be shared across the transaction; an instance variable on a helper class would not work.

References

1. Salesforce Apex Developer Guide, "Static and Instance Methods, Variables, and Initialization Code". It states, "Static variables are only static within the scope of the Apex transaction... They are not shared across transactions."

2. Salesforce Apex Developer Guide, "Triggers", section "Trigger Context Variables". The documentation on trigger execution order implicitly relies on static variables for maintaining state across different trigger events within one transaction.

Scroll to Top