Code Quality

Magic Numbers in Java: How to Replace Them

Magic numbers have no self-documenting names. Java provides static final constants and enum types as clean solutions.


❌ Java with Magic Numbers

public class ConnectionPool {
    public void initialize() {
        pool = new Pool(10, 30000, 3);
        // 10=maxConn, 30000=timeout, 3=retries — invisible!
    }
    public boolean isExpired(long createdAt) {
        return System.currentTimeMillis() - createdAt > 86400000;
    }
}

✅ Named Constants

public class ConnectionPool {
    private static final int MAX_CONNECTIONS    = 10;
    private static final int CONNECTION_TIMEOUT = 30_000;
    private static final int MAX_RETRIES        = 3;
    private static final long ONE_DAY_MS        = 86_400_000L;

    public void initialize() {
        pool = new Pool(MAX_CONNECTIONS, CONNECTION_TIMEOUT, MAX_RETRIES);
    }
    public boolean isExpired(long createdAt) {
        return System.currentTimeMillis() - createdAt > ONE_DAY_MS;
    }
}
💡

Pro tip: Java's numeric underscores (30_000) improve readability for large numbers. Use enums for finite sets: enum ConnectionState { IDLE, ACTIVE, CLOSED, ERROR }

Paste this code into LearnCodeGuide

Detect Java vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Java Code →

Related Guides

Java Long MethodJava Dead CodeJava Duplicate Code