Hardly Readable - Generic Constants
“Don’t use magic numbers.” Probably the first refactoring advice any of us was given, and one of the few nobody argues with. So we extract the 100 into a constant, give it an uppercase name - and end up with LIMIT. Sometimes that is perfectly fine. Sometimes the reader now knows neither what the number is for nor - often the more important question - whether it is 2 or 2000.
This part of the Hardly Readable series is about good reasons for extracting a constant, and bad reasons that look just like them.
A bare 3 in a loop, a 200 in a comparison, a true passed into a call - these are literals whose meaning lives only in the author’s head. Extracting them into a named constant is supposed to put that meaning into the code. There are situations in which extracting a constant really pays off - and others in which it only looks as if it did.
Good reason 1: an abstraction of a chosen value
for (int attempt = 0; attempt < MAX_RETRIES; attempt++) { ... }
MAX_RETRIES = 3 is more readable than a bare 3, because the name says why the number is there: this loop retries, and three is the cap. The number itself is a choice - it could just as well be 5, and the code would still be correct. That is what makes the constant a good abstraction: the reader needs the reason, not the value, and the value can be changed in one place without touching anything else.
Such a name must carry the reason - but the context carries part of it:
public final class Constants {
public static final int MAX_LENGTH = 32;
...
}
record Username(String value) {
static final int MAX_LENGTH = 32;
Username {
if (value.length() > MAX_LENGTH) {
throw new IllegalArgumentException("username longer than " + MAX_LENGTH + " characters");
}
}
}
Constants.MAX_LENGTH - length of what? The reader has to jump to the declaration, exactly the lookup the constant was supposed to remove. Username.MAX_LENGTH needs no jump: a username is a single string, so there is only one length it can limit. The context really has to be that specific, though - in a PageRequest(int page, int size), a LIMIT could still limit the page number or the page size. A generic name is not a problem where the context is specific; it is a problem where the context is generic, too.
Good reason 2: a label for a code
if (response.statusCode() == 200) { ... }
if (response.statusCode() == HTTP_OK) { ... }
HTTP_OK = 200 is not a choice. It can never change - and the constant is still a good idea, because 200 is not a number in the first place. It is a code, and a code has a meaning that the digits do not show. The same holds for ESC = '\u001B', for PNG_SIGNATURE - the eight bytes every PNG file starts with -, or for STATUS_ACTIVE = 'A' in a status column. Naming such a value after its meaning (HTTP_OK, not TWO_HUNDRED) is always a gain.
A true passed into a call is not a code, though:
render(page, true);
render(page, FLAG);
render(page, COMPACT);
FLAG is no better than true. COMPACT is, but a boolean behind a label is still a boolean - the name usually belongs on the method or on a type (see Boolean Flags and Mode Parameters).
Good reason 3: a shared immutable instance
This reason is not about a literal at all. Take a custom optional type:
sealed interface Option<T> permits Some, None {
static <T> Option<T> some(T value) {
return new Some<>(value);
}
@SuppressWarnings("unchecked")
static <T> Option<T> none() {
return (Option<T>) None.INSTANCE;
}
}
record Some<T>(T value) implements Option<T> {
}
final class None<T> implements Option<T> {
static final None<?> INSTANCE = new None<>();
private None() {
}
}
some(value) has to construct a new object every time, because every Some holds a different value. none() has nothing to vary - every None is the same immutable value, so a single constant can stand for all of them. The private constructor makes sure it is the only one, and so an empty option can even be recognised by identity, option == Option.none(), instead of equals. The JDK does the same with Optional.empty().
This is a micro-optimization, admittedly. But it is one that costs nothing, and it usually makes the code more readable rather than less: Option.none() names the meaning, where new None<>() only spells out a construction.
Bad reason: hiding a value that matters
A constant hides its value - that is its purpose, as long as the reader does not need the value. Sometimes they do. Take a date in the format 2026-12-05:
int year = parseInt(date.substring(0, YEAR_END));
int month = parseInt(date.substring(MONTH_START, MONTH_END));
int day = parseInt(date.substring(DAY_START));
int year = parseInt(date.substring(0, 4));
int month = parseInt(date.substring(5, 7));
int day = parseInt(date.substring(8));
The names are perfect, and still nobody can check the first version without looking up four values. That MONTH_START is where the month starts is what the name promises; whether it is 5 decides whether the code is correct - and that is exactly what the name hides. The second version can be checked against the format at a glance: four digits, a dash, two digits, a dash, two digits.
These values are not chosen in the sense of reason 1: none of them can be changed in one place, they are dictated by the format and only make sense together. Nor are they codes in the sense of reason 2: a 5 here means nothing but position 5. (A real date would be parsed with a DateTimeFormatter, of course - but every fixed-width format has the same shape, and most of them have no parser.)
Tests are the extreme case, because a test pins a value by definition:
assertThat(response.items()).hasSize(MAX_PAGE_SIZE);
assertThat(response.items()).hasSize(100);
The first assertion passes for any value, including a wrong one. The second states what we expect.
Bad reason: sharing a value that is not shared knowledge
httpClient.connectTimeout(DEFAULT_TIMEOUT);
jdbcTemplate.setQueryTimeout(DEFAULT_TIMEOUT);
lock.tryLock(DEFAULT_TIMEOUT);
Three places happen to wait 30 seconds, so the value was extracted once. But each of them could reconsider its value on its own - a slow report query needs more, a lock should give up sooner. The shared constant couples decisions that have nothing to do with each other: the first change for one silently changes the others.
The fix is not to give up the constant, but to give up the sharing. Each location deserves its own decision, and each decision is a chosen value in the sense of reason 1 - so each may well get its own constant:
httpClient.connectTimeout(CONNECT_TIMEOUT);
jdbcTemplate.setQueryTimeout(QUERY_TIMEOUT);
lock.tryLock(LOCK_TIMEOUT);
That all three are 30 seconds today is a coincidence, and three constants with the same value do not state otherwise. One constant for all three does: it claims a single decision where there are three.
Bad reason: labelling a text that is its own label
private static final String ORDER_REJECTED = "Order {} rejected: credit limit of {} exceeded";
...
log.warn(ORDER_REJECTED, order.id(), customer.creditLimit());
log.warn("Order {} rejected: credit limit of {} exceeded", order.id(), customer.creditLimit());
Messages like this one are extracted for many reasons, and hardly any of them is about the reader:
- Convention. All messages belong in constants - a rule of the team or the codebase.
- Duplication rules. Static analysis flags every string literal used three times or more.
- Overview. All texts should be in one place, to keep the wording consistent.
- Internationalisation. The text might be translated one day - which log messages never are, and if they were, a resource bundle would be the tool, not a constant.
- Tests. A test wants to assert the message without repeating it - and then passes whatever the message says.
All of them treat the text like a magic number. But a 100 is opaque, and a message is not - the inline message is its own best name.
For log messages in particular, the extraction has two concrete costs:
- Finding the code from the log. Searching for a message found in the logs leads to the constant definition, and a second search is needed to find its usages. If the constant is used in several places - which is exactly what the duplication rule asks for - the same log line now comes from several places, and the log no longer tells which one fired.
- Separating the template from its arguments. Inline, the placeholders can be matched against the arguments at a glance. Behind a constant they are hidden, and the reader has to imagine where each argument goes. Even adding one more piece of information to the message means editing two locations.
Not every extracted text has a name as poor as its content. An SQL statement usually gets a good one:
private static final String FIND_RECENT_ORDERS =
"SELECT id, total, created_at FROM orders WHERE customer_id = ? AND created_at >= ?";
...
jdbcTemplate.query(FIND_RECENT_ORDERS, orderMapper, customer.id(), since);
jdbcTemplate.query("""
SELECT id, total, created_at
FROM orders
WHERE customer_id = ? AND created_at >= ?
""", orderMapper, customer.id(), since);
FIND_RECENT_ORDERS is a real abstraction - it says what the query does. But reading this call is not about what the query does; it is about whether it fits: whether the arguments match the placeholders in number and order, whether the mapper reads the columns the query selects. That is the structure of the text, and the name hides it just as ORDER_REJECTED hides its placeholders. A name that carries the meaning is good; a text whose structure has to be checked against the surrounding code still belongs next to that code.
A text that is used in exactly one place gains nothing from being reusable. It tells the reader what happens here, like a comment that cannot go stale - and it does so best where it is.
Conclusion
The advice against magic numbers is right, but it is usually taught as a mechanical step - find the literal, extract it, name it - and the mechanical step is not what makes code readable. A constant earns its place when it
- abstracts a chosen value, which can be changed in one place without breaking anything,
- labels a code, whose value never changes but whose digits mean nothing to the reader, or
- provides a shared immutable instance, a value that exists only once and is therefore recognisable by identity.
In each of these cases the name - together with its context - tells the reader what they need at the point of use.
It does not earn its place when
- the value itself is what the reader has to check - as in a fixed-width format, or in any test assertion,
- the literal already says more than any name could - by its content or by its structure, or
- it ties together places that should each decide on their own - there, each place gets its own constant.
In the first two cases the constant only moves the meaning out of sight and adds a lookup, and the literal can stay where it was.
More
For related discussion and background, see:
- Code and Cognition - why “hard to read” has a measurable cognitive cost, and why a meaning that lives somewhere else is the expensive kind
- Literal Composition Is Not Abstraction - the same gap between extracting something and abstracting it, one level up at the method
- Boolean Flags and Mode Parameters - why a
trueat the call site needs a name for the behaviour it selects, not a constant - Avoiding magic numbers - the case for named constants, with the caveat that a constant must actually add readability -
emptyArrayAmount = 0only confuses - Don’t use non-test constants in unit tests - why a test that references a production constant passes even when the constant is wrong
- The DRY Principle and Incidental Duplication - DRY is about knowledge, not about equal-looking code, so values that are only equal by coincidence should not be merged
- Magic number (programming) - the classic rule and its common justifications