All 15 Enums questions
More in Enums
Advertisement
Java › Enums

How would you use an enum to represent a fixed set of configuration keys combined with a shared lookup method, avoiding scattered String literal keys throughout a codebase?

Intermediate

Answer

Representing configuration keys as enum constants (rather than raw String literals scattered throughout the codebase) provides compile-time safety against typos (a misspelled String key silently returns null/default at runtime, while a misspelled enum reference simply fails to compile), IDE autocomplete support for discovering all valid keys, and a natural single place to attach metadata (default value, expected type, description) to each key via enum fields.
public enum ConfigKey {
    MAX_CONNECTIONS("max.connections", "100"),
    TIMEOUT_MS("timeout.ms", "5000");

    private final String propertyName;
    private final String defaultValue;
    ConfigKey(String propertyName, String defaultValue) {
        this.propertyName = propertyName; this.defaultValue = defaultValue;
    }
    public String propertyName() { return propertyName; }
    public String defaultValue() { return defaultValue; }
}

String timeout = System.getProperty(ConfigKey.TIMEOUT_MS.propertyName(), ConfigKey.TIMEOUT_MS.defaultValue());
Real-world example A large application replaces dozens of scattered raw String configuration key literals (prone to typos) with a centralized ConfigKey enum, catching an entire class of configuration-key typo bugs at compile time that previously would have silently fallen back to default values at runtime without any warning.

Common follow-ups: How would you extend this pattern to also validate or parse the configuration value's expected type (int, boolean, etc.) per key?;What's the trade-off of this enum-based approach versus a more dynamic, externally-configurable key system?