Video in progress
What is a "magic number" in code, and what do you write instead?
A magic number is a literal value written into the code without explanation, whose meaning only the author understands (if (status == 3), * 0.12). Instead you write a named constant, an enum or a configuration value.
📖 Answer
// unclear
if (user.getAttempts() > 5 && order.getStatus() == 3) {
lockUntil = now.plusSeconds(900);
}
What are 5, 3 and 900? If someone wants to change 5 to 3, they wander through the whole project looking for it.
private static final int MAX_LOGIN_ATTEMPTS = 5;
private static final Duration LOCK_DURATION = Duration.ofMinutes(15);
if (user.getAttempts() > MAX_LOGIN_ATTEMPTS && order.getStatus() == OrderStatus.CANCELLED) {
lockUntil = now.plus(LOCK_DURATION);
}
Which tool to use when:
- an enum for a limited set of states (statuses, roles);
- a
static finalconstant for an unchanging value used in several places in the code; - configuration (
application.yml+@ConfigurationProperties) for values that may change by environment or without a redeploy (limits, timeouts).
You don't need to turn self-evident values like 0, 1, -1 or 100 (for percent) into constants. Don't overdo it.
Sign up to mark studied questions and save your progress.