如何使用许多if语句提高方法的可读性和长度? [英] How can I improve readability and length of a method with many if statements?

查看:110
本文介绍了如何使用许多if语句提高方法的可读性和长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method with 195 ifs. Here is 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");
    }
}

我可以更改if开关:

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个案例仍然很长。如何改善该方法的可读性和长度?在这种情况下哪种模式是最好的?

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?

推荐答案

创建 Map< String,Double> ,将国家/地区名称映射到相应的税率:

Create a Map<String,Double> that maps country names to their corresponding tax rates:

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

使用该地图如下:

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

这篇关于如何使用许多if语句提高方法的可读性和长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆