文かどうかはどのように多くでメソッドの読みやすさと長さを向上させることができますか?

Michu93:

私は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を変更することができます。

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例はそう長くはまだです。どのように私は、そのメソッドの可読性や長さを向上させることができますか?どのようなパターンは、この場合の最善のでしょうか?

彼らは次のとおりでした:

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=225950&siteId=1