I am dealing with some code that has consistent pattern of creating Map instances like this:
Map<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("UserName", "Value1");
valuesMap.put("FirstName", "Value2");
valuesMap.put("LastName", "Value3");
valuesMap.put("Email", "Value4");
I thought it can be made Readable like this:
Map<String, String> valuesMap = createMap(
"UserName", "Value1",
"FirstName", "Value2",
"LastName", "Value3",
"Email", "Value4"
);
With the help of following method:
private Map<String, String> createMap(String... parameters) {
Map<String, String> valueMap = new HashMap<String, String>();
if (parameters.length % 2 == 0) {
for (int i = 0; i < parameters.length; i+=2){
String key = parameters[i];
String value = parameters[i + 1];
valueMap.put(key, value);
}
} else {
throw new IllegalArgumentException("The parameters to this method must be even in number");
}
return valueMap;
}
But by doing this i am losing ability of catching errors at compile time. For example: Someone can easily do the following
Map<String, String> valuesMap = createMap(
"UserName", "Value1",
"FirstName", "Value2",
"LastName", // missing value for key
"Email", "Value4"
);
I am tempted to use more readable method, need suggestions from you guys.
Edit:
- There are many instances declared like the first example.
- Keys and values are not populated but are String decalration more like static intializers.
- Its more like a code containing multiple declarations
- Keys and Values are different on every declareation
---- @Jon Skeet Thanks for pointing out the bug.