温馨提示:本文翻译自stackoverflow.com,查看原文请点击:java - How can I improve readability and length of a method with many if statements?
design-patterns if-statement java

java - 如何使用许多if语句提高方法的可读性和长度?

发布于 2020-04-14 17:46:42

我有195个ifs的方法。这是一个简短的版本:

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");
    }
}

我可以将ifs更改为switch:

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");
    }
}

但是195例仍然很长。如何改善该方法的可读性和长度?在这种情况下哪种模式最好?

查看更多

提问者
Michu93
被浏览
92
Eran 2019-06-14 02:22

创建一个Map<String,Double>将国名映射到其相应税率的:

Map<String,Double> taxRates = new HashMap<> ();
taxRates.put("POLAND",0.23);
...

Map如下使用

private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception {
    if (taxRates.containsKey(country)) {
        return new BigDecimal(taxRates.get(country)).multiply(amount);
    } else {
        throw new Exception("Country not supported");
    }
}