Apex Lazy Load Constants
1 min readApr 11, 2019
Just a quick note to talk about a pattern to lazy load constants (similar to an old question in Stackoverflow).
Problem
Sometimes you have a class full of constants and some of those are resource intensive (CPU or memory).
Solution
Lazy load those constants:
public static final Map<String, String> ISO_TO_SYMBOL {
get {
if (ISO_TO_SYMBOL == null) {
ISO_TO_SYMBOL = new Map<String, String>{
'USD' => '$',
'CAD' => '$',
'EUR' => '€',
'GBP' => '£',
'JPY' => '¥',
'KRW' => '₩',
'CNY' => '元'
};
}
return ISO_TO_SYMBOL;
}
set;
}
Benefits
- Assure the static instance is never changed: constant.
- Load the map only if requested: lazy load.
Drawback
- More convoluted code.
Question
Is this a supported pattern or just a corner case? Asking because have not found an example online.