Sample Java properties file which is read by the properties class
appl.component1.property1=value1
appl.component1.property1=value2
Custom class which extends the java.util.Properties class adding behavior to throw an exception when a requested property is not available.
public class Configuration extends Properties {
@Override
public String getProperty(String key) {
String value = super.getProperty(key);
if (value == null) {
throw new InvalidParameterException(MessageFormat.format(
"Value missing for key {0}!", key));
}
return value;
}
}
Load properties file and retrieve the key value pairs for initial validation.
PropertiesExcep properties = new PropertiesExcep();
properties.load("file://foobar");
for(PropertyKeys key: PropertyKeys.values()){
properties.getProperty(key.getValue())
}
Enum using keys of properties
public enum PropertyKeys{
PROP1("appl.component1.property1"),
PROP2("app1.component1.property2");
private String value;
PropertyKeys(String in){
value = in_text;
}
public String getValue(){
return value;
}
}
Best Answer
The answer to your question would depend on a few things:
The biggest being: Will you ever need to add/remove a key at run-time?
If so, then an enum is unlikely to be the way to go - its values are supposed to stay constant, and this will lead to ugly code later on. Accessing the keys from the
Properties
object directly would be a lot easier.How will you be using the keys?
If you're going to be hard coding the keys in a lot, this could save a quite a bit of time and effort. Otherwise it's just a waste of time.
Is it worth having a variable for every key?
If you're going to be using a lot of keys, it's going to become a mess and a pain to maintain.
To sum it up: it isn't an anti-pattern - there is no set rule, if it isn't going to save you time, clarify the code or cut down on difficulty - it's not worth doing. If it's going to hinder you in the future by becoming a pain to use - it's bad practice.