I have an existing project based on Java in which an existing utility method is present which gets some values as an input and provides result as a boolean value.
I need to refactor this method since there is an upcoming requirement which will cause a greater number of switch cases to be introduced in this method.
I tried other possible solutions shown on other Stack Overflow questions, but those solutions were not applicable for the use case I have here.
The code snippet is mentioned below.
protected static < T extends Comparable < T >> boolean compareValues(T lookupValue, T actualValue, String comparisonCondition, List < T > lookupValues) {
comparisonCondition = comparisonCondition.toUpperCase();
boolean result;
switch (comparisonCondition) {
case EQUALS:
result = lookupValue instanceof String && actualValue instanceof String ? (String.valueOf(lookupValue).trim()).equalsIgnoreCase(String.valueOf(actualValue).trim()) : lookupValue.compareTo(actualValue) == 0;
break;
case NOT_EQUALS:
result = lookupValue.compareTo(actualValue) != 0;
break;
case LIKE:
result = StringUtils.containsIgnoreCase(String.valueOf(actualValue), String.valueOf(lookupValue));
break;
case NOT_LIKE:
result = !StringUtils.containsIgnoreCase(String.valueOf(actualValue), String.valueOf(lookupValue));
break;
case IN:
result = lookupValues.stream().anyMatch(lkpValue - > lkpValue instanceof String ? ((String) lkpValue).trim().compareToIgnoreCase(String.valueOf(actualValue).trim()) == 0 : lkpValue.compareTo(actualValue) == 0);
break;
case NOT_IN:
result = lookupValues.stream().noneMatch(lkpValue - > lkpValue instanceof String ? ((String) lkpValue).trim().compareToIgnoreCase(String.valueOf(actualValue).trim()) == 0 : lkpValue.compareTo(actualValue) == 0);
break;
default:
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MSG_FORMAT_INVALID_COMPARISON_CONDITION, comparisonCondition);
}
result = false;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Comparing value '{}' with '{}' using comparison condition '{}'.{}Result: {}", actualValue, Objects.nonNull(lookupValue) ? lookupValue : lookupValues.stream().map(Object::toString).collect(Collectors.joining(WhlProcessingConstants.SPLIT_COMMA)), comparisonCondition, LINE_SEPARATOR, result);
}
return result;
}
Can you please suggest some solution by which this code of the method can be refactored, so that it is scalable for any future requirements and also, the cognitive complexity will not increase as we include more comparisonConditions / cases in it?
For your information: I am using SonarLint plugin to analyze the cognitive complexity of the code.