Home > Software design >  handle multiple if to get rid of Cyclomatic Complexity
handle multiple if to get rid of Cyclomatic Complexity

Time:05-24

I want to handle multiple if conditions to get rid of Cyclomatic Complexity. please help:

BigDecimal totalValue = null;     
 if (null != truckValue && truckValue.compareTo(BigDecimal.ZERO) > 0 && null != buggyContents && buggyContents.compareTo(BigDecimal.ZERO) > 0) {
            totalValue = mainValue.add(truckValue).add(buggyContents);
        } else if (null == buggyContents || buggyContents.compareTo(BigDecimal.ZERO) < 0 && null == truckValue || truckValue.compareTo(BigDecimal.ZERO) < 0) {
            totalValue = mainValue;
        } else if (truckValue.compareTo(BigDecimal.ZERO) < 0 || truckValue == null) {
            totalValue = mainValue.add(buggyContents);
        } else if (buggyContents.compareTo(BigDecimal.ZERO) < 0 || buggyContents == null) {
            totalValue = mainValue.add(truckValue).add(buggyContents);
        }
        return totalValue;

CodePudding user response:

Probably you're looking for something like:

BigDecimal totalValue = mainValue;
if (null != truckValue && truckValue.compareTo(BigDecimal.ZERO) > 0)
    totalValue = totalValue.add(truckValue);
if (null != buggyContents && buggyContents.compareTo(BigDecimal.ZERO) > 0)
    totalValue = totalValue.add(buggyContents);
return totalValue;

probably you want to summarize all non null values? then just remove comparison with zero:

BigDecimal totalValue = mainValue;
if (null != truckValue) totalValue = totalValue.add(truckValue);
if (null != buggyContents) totalValue = totalValue.add(buggyContents);
return totalValue;

CodePudding user response:

Assuming that you want to add truckValue and buggyContents to mainValue, but only if the values are neither null nor negative and you want to return the sum, you can do without the whole if-else block by using strems:

import java.math.BigDecimal;
import java.util.Objects;
import java.util.stream.Stream;

....


public BigDecimal yourMethod(/* whatever */) {
    return Stream.of(truckValue, buggyContents)
                 .filter(Objects::nonNull)
                 .filter(bigDecimal -> bigDecimal.signum() != -1)
                 .reduce(mainValue, BigDecimal::add);
}
  • Related