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