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"); } }
I can change ifs to switches:
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"); } }
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?
You can make multiple if statements behave like a single if else-if .. else statement if each of the condition blocks breaks out of the block that contains the if statements (for example, by returning from the method or breaking from a loop).
In order to accurately determine a text’s readability, many factors need to be considered and calculated. Precise computer algorithms are formulated to analyze multiple components of a text including word count, sentence length, characters per word, etc. Several of the most widely used readability scoring methods are listed and explained below.
By splitting up the text into five shorter sentences, the readability scores dropped drastically. Now, the Flesch-Kincaid Grade Level is dropped by 14.3 points to a much more reasonable 14.1. Similarly, the Gunning-Fog score dropped by 12.8 points to a new score of 18.4.
Along with sentence length, the other key component of readability formula is word length. For some tests such as Flesch- Kincaid, calculate word length on the number of syllables. For others such as Coleman-Liau, word length is calculated on letter count.
By ensuring the readability of a piece of text – a patient care guide, a promotional piece for a particular brand, a policy – you increase the chances of your message being understood by your reader. If you are writing text for the general public you should aim for a grade level score of around 8.
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); ...
Use that Map
as follows:
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With