I am here to seek help w.rt. simplifying if-elseif statements in java. Here's my code below, which has numerous if, elseifs. Is it possible to simplify the below code using java lambda features? Can I reduce if, elseif statements in my method? Can we use Java 8 filter functionality here?
public ReturnsRetailerConfigPromotionResponse promoteRetailerConfig(
ReturnsRetailerConfigPromotionRequest returnsRetailerConfigPromotionRequest,
String configType) {
try{
if(isTenantConfigPromotion){
tenantDetails = returnsGenericUtils.getTenantConfig(sourceRetailerName, sourceHubLoginResponse);
}
else if(isTrackConfigPromotion){
returnsGenericUtils.downloadTrackConfig(sourceRetailerName, sourceHubcookies);
}
else if(isReturnRulesPromotion){
returnsGenericUtils.downloadReturnRules(sourceRetailerName, sourceHubcookies);
}
else if(isReturnReasonsPromotion){
returnsGenericUtils.downloadReturnReasons(sourceRetailerName, sourceHubcookies);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return new ReturnsRetailerConfigPromotionResponse(...);
}
}
At first, I would remove redundant "else if" statements, if the only 'true' case is possible, like this:
if(isTenantConfigPromotion){
tenantDetails = returnsGenericUtils.getTenantConfig(sourceRetailerName, sourceHubLoginResponse);
}
if(isTrackConfigPromotion){
returnsGenericUtils.downloadTrackConfig(sourceRetailerName, sourceHubcookies);
}
if(isReturnRulesPromotion){
returnsGenericUtils.downloadReturnRules(sourceRetailerName, sourceHubcookies);
}
if(isReturnReasonsPromotion){
returnsGenericUtils.downloadReturnReasons(sourceRetailerName, sourceHubcookies);
}
And then I would think about moving the block somewhere else, cause` it looks like a side effect:
if(isTenantConfigPromotion){
tenantDetails = ..
}
If you realy want to use lambdas here, than you can try to transform boolean conditions into text values, and make something like:
private static final Map<String, BiConsumer<Object, Object>> DOWNLOADERS_MAPPING = Map.of(
"isTrackConfigPromotion", returnsGenericUtils::getTenantConfig,
"isReturnRulesPromotion", returnsGenericUtils::downloadReturnRules,
"isReturnReasonsPromotion", returnsGenericUtils::downloadReturnReasons
);
public ReturnsRetailerConfigPromotionResponse promoteRetailerConfig(
ReturnsRetailerConfigPromotionRequest returnsRetailerConfigPromotionRequest,
String configType,
Set<String> conditions
) {
try {
conditions.forEach(condition -> {
DOWNLOADERS_MAPPING.getOrDefault(condition, returnsGenericUtils::doNothing).accept(sourceRetailerName, sourceHubcookies);
});
} catch (Exception e) {
log.error(e.getMessage(), e);
return new ReturnsRetailerConfigPromotionResponse(...);
}
}
than it's gonna be easier to extend the method if you get more conditions.