jeudi 13 juin 2019

Many if's statements

I have a method with 195 if's. I post a shorter version:

private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception {
        if(country.equals("POLAND")){
            return new BigDecimal(0.23).multiply(amount);
        }
        else if(country.equals("AUSTRIA")) {
            return new BigDecimal(0.20).multiply(amount);
        }
        else if(country.equals("CYPRUS")) {
            return new BigDecimal(0.19).multiply(amount);
        }
        else {
            throw new Exception("Country not supported");
        }
    }

I can change if's to switches:

 private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception {
        switch (country) {
            case "POLAND":
                return new BigDecimal(0.23).multiply(amount);
            case "AUSTRIA":
                return new BigDecimal(0.20).multiply(amount);
            case "CYPRUS":
                return new BigDecimal(0.19).multiply(amount);
            default:
                throw new Exception("Country not supported");
        }
    }

but 195 cases is still so long. How could I improve readability and length of that method? What pattern would be the best in this case?

Aucun commentaire:

Enregistrer un commentaire