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

编程入门 行业动态 更新时间:2024-10-27 10:33:08
本文介绍了如何使用许多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语句提高方法的可读性和长度?

本文发布于:2023-11-06 01:51:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562418.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可读性   如何使用   语句   长度   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!