This method invokes different validation methods for every textfield in a form and the int[] array in the Map decides which methods or what type of validations is to be done on a textfield. But this method has cyclomatic complexity of 10. Please suggest any better alternatives or what can be done to improve this code ?
public final boolean validateFields(final HashMap<JTextField, int[]> textFieldMap) {
boolean flag = false;
for (Map.Entry<JTextField, int[]> entry : textFieldMap.entrySet()) {
JTextField field = entry.getKey();
for (int constant : entry.getValue()) {
switch (constant) {
case Constants.VAL_CHAR : flag = validateChar();
break;
case Constants.VAL_DATE : flag = validateDate();
break;
case Constants.VAL_DUPLICATE : flag = validateDuplicate();
break;
case Constants.VAL_EMAIL : flag = validateEmail();
break;
case Constants.VAL_LENGTH : flag = validateLength();
break;
case Constants.VAL_NUMERIC : flag = validateNumeric();
break;
case Constants.VAL_STRING : flag = validateNumeric();
break;
default : flag = validateNotNull();
break;
}
}
}
return flag;
}
I don’t know if this is applicable to your case, but you could use an enum instead of int constants:
You can then refactor your code like this:
Or just get rid of the ints:
PS: in your current code, you probably mean
flag = flag && validateXXX()unless you only want to return the flag corresponding to the last checked field.