Is there a way to optimize the code below:
public BigDecimal calculate(Policy policy) {
BigDecimal total = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_EVEN);
for (PolicyObject policyObject : policy.getPolicyObjects()) {
for (PolicySubObject policySubObject : policyObject.getPolicySubObjects()) {
for (Risk risk : policySubObject.getRisks()) {
for (Rate rate : risk.getRates()) {
// CompareTo returns -1 if BigDecimal is smaller then to compared Big decimal
// 0 if equals and 1 if greater.
if (policySubObject.getSumInsured().compareTo(rate.getRangeStart()) >= 0
&& policySubObject.getSumInsured().compareTo(rate.getRangeEnd()) < 0) {
total = total.add(policySubObject.getSumInsured().multiply(rate.getPremiumRate()));
}
}
}
}
}
return total;
}
4 nested loops all together with a condition look very disturbing. Ultimately there is a need to go over each rate to calculate the premium I couldn`t find a better way to do it.
It seems there is no obvious solution here, If loops are necessary here there is no way to get rid of them.