Sub topic 8
Constants with final and static final
This chapter assumes you can declare Apex classes, that you know instance members from static members, and that you have used List, Set, and Map. It covers the final keyword, the static final constant pattern, and the mistakes that most often trip people up.
What final does
The final keyword says a variable can be assigned only once. After that assignment, the variable cannot point to a different value. You can use it on member variables and on local variables. In Apex, classes and methods are already final by default. You open them for extension with virtual or abstract, so you never write final on a class or method.
public class FinalBasics {
public static void demo() {
final Integer retries = 3;
System.debug(retries); // 3
// retries = 4; // compile error: a final variable cannot be reassigned
}
}The compiler reports the reassignment when you save the class. Nothing fails at runtime, which makes final a cheap safety check.
Where a final variable can be assigned
The place of the single assignment depends on the kind of variable.
| Kind of variable | Where you can assign it |
|---|---|
| Local `final` variable | At declaration, or once later in the same method |
| Instance `final` field | At declaration, in an instance initialization block, or in a constructor |
| `static final` field | At declaration, or in a static initialization block |
Instance final fields
An instance final field gives each object a value that is fixed when the object is built. Different objects can hold different values. This suits settings that must not change after construction.
public class RetryPolicy {
public final Integer maxAttempts;
public final String label;
public RetryPolicy(Integer maxAttempts, String label) {
this.maxAttempts = maxAttempts;
this.label = label;
}
public Boolean canRetry(Integer attemptsSoFar) {
return attemptsSoFar < maxAttempts;
}
}
// Usage
RetryPolicy quick = new RetryPolicy(2, 'quick');
RetryPolicy patient = new RetryPolicy(10, 'patient');
System.debug(quick.canRetry(2)); // false
System.debug(patient.canRetry(2)); // trueBecause the fields are final, no other method in RetryPolicy can change them. A caller that holds a RetryPolicy can read maxAttempts but cannot overwrite it. The PercentDiscount class from the interfaces chapter uses the same technique, with private final Decimal percent set in its constructor.
static final constants
A static final field belongs to the class and cannot be reassigned, so it gives you a named constant. The convention is UPPER_SNAKE_CASE, and you read the constant through the class name.
public class OrderRules {
public static final Integer MAX_LINES = 50;
public static final String STATUS_DRAFT = 'Draft';
public static final String STATUS_ACTIVATED = 'Activated';
public static final Decimal TAX_RATE = 0.2;
public static Boolean canAddLine(Integer currentLines) {
return currentLines < MAX_LINES;
}
}
// Usage
System.debug(OrderRules.canAddLine(49)); // true
System.debug(OrderRules.canAddLine(50)); // false
System.debug(OrderRules.STATUS_DRAFT); // DraftNamed constants have three benefits over repeating literals such as 50 or 'Draft':
- A typo in a constant name fails at compile time, while a typo inside a string literal fails silently at runtime.
- You change a value in one place.
- The name explains the number.
MAX_LINEStells the reader more than50.
Instance final versus static final
A plain final field without static is allocated for every object, even when every object gets the same value. If a value is the same for all objects, make it static final. If it varies per object but must not change, make it an instance final field.
public class Invoice {
public static final String CURRENCY_CODE = 'USD'; // same for every Invoice
public final Id accountId; // different per Invoice
public Invoice(Id accountId) {
this.accountId = accountId;
}
}Computed constants and static blocks
Some constants cannot be built with one simple expression. Apex has no immutable-set literal, so the usual way to fill a collection constant is a static initialization block. The block runs once, the first time the class is used in a transaction, and it is the one place besides the declaration where a static final field can be assigned.
public class CaseRules {
public static final Set<String> CLOSED_STATUSES;
public static final Integer CLOSED_COUNT;
static {
CLOSED_STATUSES = new Set<String>{ 'Closed', 'Resolved', 'Cancelled' };
CLOSED_COUNT = CLOSED_STATUSES.size();
}
public static Boolean isClosed(String status) {
return CLOSED_STATUSES.contains(status);
}
}
// Usage
System.debug(CaseRules.isClosed('Resolved')); // true
System.debug(CaseRules.isClosed('New')); // false
System.debug(CaseRules.CLOSED_COUNT); // 3Static blocks run in the order they appear in the class. A later block can use values assigned by an earlier one, as CLOSED_COUNT does here.
Gotchas
final does not make a collection immutable
final fixes the reference, not the contents. A final list, set, or map can still be changed through its methods.
public class CollectionGotcha {
public static final List<String> COLORS = new List<String>{ 'red', 'green' };
public static void demo() {
COLORS.add('blue'); // allowed: the list object is modified
System.debug(COLORS); // (red, green, blue)
// COLORS = new List<String>(); // compile error: reassignment
}
}Any code that can see the field can add to it or clear it, and the change stays visible to every later caller in the same transaction. To reduce the risk, make the field private and expose a method that returns a copy, or call makeReadOnly() on a list inside the static block. makeReadOnly() makes later add, remove, and set operations on that list throw a runtime exception.
public class SafeColors {
private static final List<String> COLORS;
static {
COLORS = new List<String>{ 'red', 'green' };
COLORS.makeReadOnly();
}
public static List<String> getColors() {
return COLORS.clone();
}
}Constants are evaluated per transaction
A static final field is not computed at deploy time. It is computed when the class is first used in each transaction. The value is therefore fixed for that transaction and recalculated in the next one.
public class RunInfo {
public static final Datetime STARTED_AT = Datetime.now();
}Every read of RunInfo.STARTED_AT within one transaction returns the same moment, even if the code runs for several seconds. A later transaction gets a new value. This is a convenient way to get a consistent timestamp, but it is not a deploy-time constant.
final on a variable is not final on an SObject
final Account a = new Account(Name = 'Acme'); stops you from pointing a at another Account. You can still write a.Name = 'Other';, because the object's fields are not final.
Choosing between constants and enums
String constants such as STATUS_DRAFT are good for values that must match data stored in Salesforce, such as picklist values. When a value is purely internal and has a fixed set of options, an enum gives you compile-time checking that a plain String cannot.
flowchart TDCommon errors
- Assigning a
static finalfield from a regular method. Assignment is allowed only at the declaration or in a static block. - Expecting a
finalcollection to be read-only. Only the reference is fixed. - Using
finalinstance fields for values that are the same everywhere. Usestatic finalso the value is stored once for the class. - Putting the same literal in many classes. Define it once in a constants class and refer to it as
OrderRules.MAX_LINES.
Exercise
A class declares public static final List<String> TIERS = new List<String>{ 'Gold', 'Silver' };. A teammate runs OrderRules.TIERS.add('Bronze'); in another class. Does this compile, and what is the state of TIERS afterward? How would you stop it?
Show answer
It compiles and runs, because final only prevents assigning a new list to TIERS. The list now holds Gold, Silver, and Bronze for the rest of the transaction, and every caller sees the change. To prevent it, make the field private, build it in a static block, and call makeReadOnly() on it. Expose a method that returns TIERS.clone() so callers get a copy they can change safely.
Exercise
You need a constant holding today's date, used by many methods in one class, and you want every method in one transaction to see the same value. Which declaration fits, and when is the value computed?
Show answer
Use public static final Date TODAY = Date.today();. Apex computes it once, when the class is first used in the transaction, so every method in that transaction sees the same date. The next transaction computes it again.