I want to check if the length of phone number is appropriate for specified country (let's consider that only some countries have restriction, another countries accept phone number with various length). I have a Map, where the correct pairs are defined so this map can be used as a reference in the condition:
public static ErrCode checkStatePhoneLen(final String state, final String phoneNo)
{
String stateTmp = state.trim();
String phoneTmp = phoneNo.trim();
Integer phoneLen = new Integer(phoneTmp.length());
if ( statePhoneNoMap.containsKey(stateTmp) && !phoneLen.equals(statePhoneNoMap.get(stateTmp)))
{
return ERROR;
}
return SUCCESS;
}
My questions are:
- Is it better to use temporary variables or directly usage of already existed object? I can just use "
state.trim()" instead of creating the variablestate_tmpand so on. I think that advantages of the solution with temporary variables are better readability and debugging but disadvantages are the effort to create new variable by runtime (or is it optimized someway by compiler?) and more rows of code (but I prefer readability factor more than number of rows factor). is it better to check if map contains the key and then compare, or to get value for given key and then check if it is not null and compare them? As following example:
Integer definedLen = (Integer) statePhoneNoMap.get(stateTmp);if (definedLen != null && !definedLen.equals(phoneLen)){
In this code sample, there is needed one more variable, but the condition is clearer. And, there is just one operation upon map (get()) instead of two in previous code (containsKey(), get())
What is better solution? How would you modify this function?