PDI · Question #62
A developer has an integer variable called maxAttempts. The developer meeds to ensure that once maxAttempts is initialized, it preserves its value for the lenght of the Apex transaction; while being…
The correct answer is C. Declare maxattempts as a constant using the static and final keywords. To ensure an integer variable maxAttempts maintains a fixed value throughout an Apex transaction and is shared across all trigger executions, it should be declared as a static final variable.
Question
A developer has an integer variable called maxAttempts. The developer meeds to ensure that once maxAttempts is initialized, it preserves its value for the lenght 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?
Options
- ADeclare maxattempts as a member variable on the trigger definition.
- BDeclare maxattempts as a private static variable on a helper class
- CDeclare maxattempts as a constant using the static and final keywords
- DDeclare maxattempts as a variable on a helper class
How the community answered
(51 responses)- A2% (1)
- B4% (2)
- C88% (45)
- D6% (3)
Why each option
To ensure an integer variable `maxAttempts` maintains a fixed value throughout an Apex transaction and is shared across all trigger executions, it should be declared as a `static final` variable.
A member variable on the trigger definition would be re-initialized for each separate trigger invocation within a transaction, failing to preserve its value across executions.
A `private static` variable on a helper class would preserve its value and be shared within the transaction, but without the `final` keyword, its value could potentially be modified, which might contradict the intent of 'preserves its value' if it's meant to be a constant.
Declaring a variable as `static final` makes it a constant, meaning its value is initialized once and cannot be changed thereafter, fitting the 'preserves its value' requirement. Being `static`, this constant value is associated with the class, not an instance, ensuring it persists and is shared across all trigger executions and other Apex code within the same transaction.
A non-static member variable on a helper class would require an instance of the class, and its value would not be automatically shared or preserved across independent trigger executions within the same transaction.
Concept tested: Apex `static` and `final` keywords for transaction scope and constants
Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_static.htm
Topics
Community Discussion
No community discussion yet for this question.