Sub topic 8
Constants with final
This chapter assumes you can declare typed variables and know the difference between local variables and class members. It also assumes you can run Anonymous Apex in the Developer Console or an IDE. By the end you should be able to declare constants, say where each kind may be assigned, and explain why final does not make an object immutable.
What final does
Apex has no const keyword. You mark a variable with final to say it can be assigned only once. Any later assignment is a compile-time error, so the mistake shows up when you save, not when the code runs.
final Integer MAX_RETRIES = 3;
Integer attempts = 0;
attempts += 1;
System.debug(attempts < MAX_RETRIES);
// MAX_RETRIES = 5; // compile error: the variable is finalThe convention is UPPERSNAKECASE for constants. The compiler does not require it, but it lets a reader see at once that a name is not meant to change.
Where a final variable can be assigned
The allowed places depend on what kind of variable it is.
| Kind of variable | Where it can be assigned |
|---|---|
| Local variable | In its declaration |
| Instance member (`public final String name;`) | In the declaration, in the constructor, or in an instance initializer block |
| Static member (`public static final ...`) | In the declaration, or in a static initializer block |
Whichever place you use, the assignment must happen exactly once.
Class-level constants
Constants shared by a whole class are usually static final. A static member belongs to the class, not to each object, so there is one copy.
public class RetryPolicy {
public static final Integer MAX_RETRIES = 3;
public static final Set<String> RETRYABLE = new Set<String>{ 'TIMEOUT', 'LOCKED' };
public final String name;
public RetryPolicy(String name) {
this.name = name;
}
public Boolean shouldRetry(Integer attempts, String errorCode) {
return attempts < MAX_RETRIES && RETRYABLE.contains(errorCode);
}
}name is an instance member. It gets a different value for each object, but only once, in the constructor. Code elsewhere reads the constant as RetryPolicy.MAX_RETRIES.
Anonymous Apex test:
RetryPolicy policy = new RetryPolicy('orders');
System.debug(policy.shouldRetry(1, 'TIMEOUT'));
System.debug(policy.shouldRetry(3, 'TIMEOUT'));
System.debug(RetryPolicy.MAX_RETRIES);The output is true, false, and 3.
Static initializer blocks
When the value takes more than one expression to build, declare the variable and assign it in a static block.
public class Priorities {
public static final Map<String, Integer> LEVELS;
static {
LEVELS = new Map<String, Integer>();
LEVELS.put('High', 1);
LEVELS.put('Medium', 2);
LEVELS.put('Low', 3);
}
}The block runs once, when the class is first used in a transaction. The same is true of a constant whose declaration calls a method, such as public static final Date LOADED_ON = Date.today();. The value is fixed for that transaction, not for all time, because static state does not persist between transactions.
final protects the variable, not the object
final stops you from pointing the variable at a different value. It does not stop the object from changing. This is the most common misunderstanding at this level.
final List<String> names = new List<String>{ 'a' };
names.add('b');
System.debug(names.size());
// names = new List<String>(); // compile error: reassignmentThe output is 2. The list is the same list, but its contents changed. The same applies to sets, maps, and SObjects. A final Account acc can still have acc.Name modified.
| Operation on a final variable | Allowed? |
|---|---|
| Reassign it to another value or object | No |
| Add to or remove from a final collection | Yes |
| Change a field on a final SObject | Yes |
| Read it anywhere it is visible | Yes |
For a primitive such as Integer or String, the two ideas happen to coincide, because those values cannot change in place. For collections and SObjects they do not.
Making a list truly read-only
If a shared list must not change, call makeReadOnly() after you fill it. Later changes throw a System.FinalException. The call cannot be undone, so use it only when the contents are complete.
final List<String> codes = new List<String>{ 'A', 'B' };
codes.makeReadOnly();
try {
codes.add('C');
} catch (System.FinalException e) {
System.debug('Blocked: ' + e.getMessage());
}
System.debug(codes.size());The add call is blocked and the size stays 2. makeReadOnly() is a method on List. Do not assume that sets and maps have an equivalent. For those, keep the collection private and expose only read methods such as contains or get.
final on classes and methods
The keyword also appears with classes and methods, but there the default differs. In Apex, a class cannot be extended and a method cannot be overridden unless you declare it virtual or abstract. So code rarely needs to write final there. Adding final to a method simply makes explicit that it cannot be overridden. This chapter is about variables, so the rest of this section applies only to them.
Constants versus enums
Both express fixed values. Pick by what the value represents.
- Use a
static finalconstant for a single number, string, or limit, such as a retry count or an API version. - Use an enum when a variable must hold one of a closed set of named options, such as
Season.WINTER. The compiler rejects values outside the set. - Avoid several related
static final Stringconstants standing in for an enum. An enum catches typos at compile time. A string constant does not.
Common errors
- Assigning a final variable twice, or assigning it somewhere its kind does not allow, for example a static final in a constructor. Fix it by moving the assignment to the declaration or a static block.
- Declaring
final Integer x;for a local variable and never assigning it. Use the value at declaration. - Treating a final collection as protected. It is only protected against reassignment.
- Putting constants in a class that also holds heavy logic. A small class named for its purpose, such as
RetryPolicy, keeps constants easy to find.
Exercise
A class declares public static final List<String> STATUSES = new List<String>{ 'New' };. Another method runs STATUSES.add('Closed'); and then STATUSES = new List<String>();. Which line compiles and which does not? Name one way to prevent the first.
Show answer
STATUSES.add('Closed'); compiles and runs, because final only blocks reassignment and does not freeze the list. STATUSES = new List<String>(); is a compile error because the variable is final. To prevent the add, call makeReadOnly() on the list after filling it (a later add then throws System.FinalException), or keep the list private and expose read-only methods.
Exercise
You need public static final Map<String, Integer> LEVELS filled with three entries. A single declaration with an initializer would be hard to read. Where can you assign the map instead, and how many times?
Show answer
In a static { ... } initializer block in the same class, assigned exactly once. You can build the map inside the block with new Map<String, Integer>() and put calls, as in the Priorities example. The block runs once when the class is first used in the transaction.