How can I improve readability and length of a method with many if statements?Avoiding != null statementsWhy can't I use switch statement on a String?Why do this() and super() have to be the first statement in a constructor?Available locale display country when “inLocale” is set to Turkish (JDK 1.6.0_29)?Java, return new MyException: anti-pattern?how to return with if and switch statements in function bodyConverting many 'if else' statements to a cleaner approachParameters is passing default value in TestNGJava method contains another method that throws exceptionJava sorting based on object one property with some condition

Digital signature that is only verifiable by one specific person

Why can't we feel the Earth's revolution?

How to avoid offending original culture when making conculture inspired from original

How can I detect if I'm in a subshell?

How do I say what something is made out of?

What things do I only get a limited opportunity to take photos of?

Is it possible to have battery technology that can't be duplicated?

A Tale of Snake and Coffee

Are soroban (Japanese abacus) classes worth doing?

How do you translate “talk shit”?

Do items with curse of vanishing disappear from shulker boxes?

Can artificial satellite positions affect tides?

Can I appeal credit ding if ex-wife is responsible for paying mortgage?

How to address players struggling with simple controls?

Was the Lonely Mountain, where Smaug lived, a volcano?

Sakkāya-Ditthi and Self-View

Can I give my friend the sour dough "throw away" as a starter to their sourdough starter?

Are there any rules for identifying what spell an opponent is casting?

Is it possible for underground bunkers on different continents to be connected?

Basic power tool set for Home repair and simple projects

Arcane Tradition and Cost Efficiency: Learn spells on level-up, or learn them from scrolls/spellbooks?

Should I move out from my current apartment before the contract ends to save more money?

...and then she held the gun

Why is gun control associated with the socially liberal Democratic party?



How can I improve readability and length of a method with many if statements?


Avoiding != null statementsWhy can't I use switch statement on a String?Why do this() and super() have to be the first statement in a constructor?Available locale display country when “inLocale” is set to Turkish (JDK 1.6.0_29)?Java, return new MyException: anti-pattern?how to return with if and switch statements in function bodyConverting many 'if else' statements to a cleaner approachParameters is passing default value in TestNGJava method contains another method that throws exceptionJava sorting based on object one property with some condition






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








7















I have a method with 195 if's. 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 if's 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?










share|improve this question



















  • 14





    Use java.util.Map ... ?

    – Oleksandr
    8 hours ago






  • 1





    Yeah, a map or a dictionary is probably your best bet here.

    – ncbvs
    8 hours ago











  • Good point guys, but can I also put a design pattern here? Let's say that I am forced to

    – Michu93
    8 hours ago











  • You would probably be best off loading in a csv from disk, then storing it in a map.

    – JClassic
    8 hours ago






  • 6





    Warning: avoid using float point numbers with BigDecimal. BigDecimal(0.23) might not be the same as BigDecimal(23)/BigDecimal(100). The latter is the correct representation of 23%.

    – gudok
    8 hours ago

















7















I have a method with 195 if's. 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 if's 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?










share|improve this question



















  • 14





    Use java.util.Map ... ?

    – Oleksandr
    8 hours ago






  • 1





    Yeah, a map or a dictionary is probably your best bet here.

    – ncbvs
    8 hours ago











  • Good point guys, but can I also put a design pattern here? Let's say that I am forced to

    – Michu93
    8 hours ago











  • You would probably be best off loading in a csv from disk, then storing it in a map.

    – JClassic
    8 hours ago






  • 6





    Warning: avoid using float point numbers with BigDecimal. BigDecimal(0.23) might not be the same as BigDecimal(23)/BigDecimal(100). The latter is the correct representation of 23%.

    – gudok
    8 hours ago













7












7








7








I have a method with 195 if's. 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 if's 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?










share|improve this question
















I have a method with 195 if's. 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 if's 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?







java design-patterns






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 40 secs ago









Laurel

4,847102239




4,847102239










asked 8 hours ago









Michu93Michu93

1,05311533




1,05311533







  • 14





    Use java.util.Map ... ?

    – Oleksandr
    8 hours ago






  • 1





    Yeah, a map or a dictionary is probably your best bet here.

    – ncbvs
    8 hours ago











  • Good point guys, but can I also put a design pattern here? Let's say that I am forced to

    – Michu93
    8 hours ago











  • You would probably be best off loading in a csv from disk, then storing it in a map.

    – JClassic
    8 hours ago






  • 6





    Warning: avoid using float point numbers with BigDecimal. BigDecimal(0.23) might not be the same as BigDecimal(23)/BigDecimal(100). The latter is the correct representation of 23%.

    – gudok
    8 hours ago












  • 14





    Use java.util.Map ... ?

    – Oleksandr
    8 hours ago






  • 1





    Yeah, a map or a dictionary is probably your best bet here.

    – ncbvs
    8 hours ago











  • Good point guys, but can I also put a design pattern here? Let's say that I am forced to

    – Michu93
    8 hours ago











  • You would probably be best off loading in a csv from disk, then storing it in a map.

    – JClassic
    8 hours ago






  • 6





    Warning: avoid using float point numbers with BigDecimal. BigDecimal(0.23) might not be the same as BigDecimal(23)/BigDecimal(100). The latter is the correct representation of 23%.

    – gudok
    8 hours ago







14




14





Use java.util.Map ... ?

– Oleksandr
8 hours ago





Use java.util.Map ... ?

– Oleksandr
8 hours ago




1




1





Yeah, a map or a dictionary is probably your best bet here.

– ncbvs
8 hours ago





Yeah, a map or a dictionary is probably your best bet here.

– ncbvs
8 hours ago













Good point guys, but can I also put a design pattern here? Let's say that I am forced to

– Michu93
8 hours ago





Good point guys, but can I also put a design pattern here? Let's say that I am forced to

– Michu93
8 hours ago













You would probably be best off loading in a csv from disk, then storing it in a map.

– JClassic
8 hours ago





You would probably be best off loading in a csv from disk, then storing it in a map.

– JClassic
8 hours ago




6




6





Warning: avoid using float point numbers with BigDecimal. BigDecimal(0.23) might not be the same as BigDecimal(23)/BigDecimal(100). The latter is the correct representation of 23%.

– gudok
8 hours ago





Warning: avoid using float point numbers with BigDecimal. BigDecimal(0.23) might not be the same as BigDecimal(23)/BigDecimal(100). The latter is the correct representation of 23%.

– gudok
8 hours ago












4 Answers
4






active

oldest

votes


















13














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







share|improve this answer




















  • 1





    This doesn't seem like a reasonable place to throw a checked exception. I know that OP's code does this, but I'd still rather not propagate it.

    – Ben P.
    8 hours ago






  • 4





    @BenP. I see no issue with throwing a checked exception if you receive an unexpected/not supported input. I'd probably use some custom exception and not the base Exception class though.

    – Eran
    8 hours ago











  • Or alternatively Optional.ofNullable(taxRateMap.get(country)) .mapping(taxRate -> new BigDecimal(taxRate).multiply(amount); .orElseThrow( () -> new Exception("Country " + country + " not supported"));

    – davidxxx
    7 hours ago











  • An IllegalArgumentException should be fine, but a plain Exception is a no-go...

    – Marco13
    6 hours ago


















5














Put the data in an XML file or database, then use it to populate a dictionary. That way you can change the data easily, and separate the data from your application logic. Or, just execute a SQL query in your method instead.






share|improve this answer






























    1














    If the values are constant and are not meant to be changed regularly (which I doubt). I'd introduce a static metamodel using Enum:



    public enum CountryList 

    AUSTRIA(BigDecimal.valueOf(0.20)),
    CYPRUS(BigDecimal.valueOf(0.19)),
    POLAND(BigDecimal.valueOf(0.23));

    private final BigDecimal countryTax;

    CountryList(BigDecimal countryTax)
    this.countryTax = countryTax;


    public BigDecimal getCountryTax()
    return countryTax;


    public static BigDecimal countryTaxOf(String countryName)
    CountryList country = Arrays.stream(CountryList.values())
    .filter(c -> c.name().equalsIgnoreCase(countryName))
    .findAny()
    .orElseThrow(() -> new IllegalArgumentException("Country is not found in the dictionary: " + countryName));

    return country.getCountryTax();




    Then



    private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception 
    return CountryList.countryTaxOf(country).multiply(amount);



    It's readable, compile time safe, easily extendable with additional metadata per country and less boilerplate.






    share|improve this answer























    • Why the stream?

      – immibis
      27 mins ago


















    0














    You may consider creating two arrays. It is easy to implement. For instance, in this case you may use :
    String[] countries = "Poland", "India", "Mexico",....;
    And another array for the respective BigDecimalvalue.
    BigDecimal[] taxrates = 0.23,0.5,0.75;
    Notice that since both the arrays are parallel, the value of index for both the arrays would be same for whichever is selected. For instance, index = 1 would always point to India and 0.5.
    In case you need to remove or add an element from the array, you can use a temporary array and copy the values. Then create a new array and copy the required values. You can also edit values using index like using SQL id. In case of dynamic and drastic changes I suggest using ArrayList where we can easily access get() and indexOf("") or remove("") methods.
    There maybe better approaches but I personally find this easy to implement.
    P.S. - Hashmap may also be used to solve the problem.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56586432%2fhow-can-i-improve-readability-and-length-of-a-method-with-many-if-statements%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      13














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







      share|improve this answer




















      • 1





        This doesn't seem like a reasonable place to throw a checked exception. I know that OP's code does this, but I'd still rather not propagate it.

        – Ben P.
        8 hours ago






      • 4





        @BenP. I see no issue with throwing a checked exception if you receive an unexpected/not supported input. I'd probably use some custom exception and not the base Exception class though.

        – Eran
        8 hours ago











      • Or alternatively Optional.ofNullable(taxRateMap.get(country)) .mapping(taxRate -> new BigDecimal(taxRate).multiply(amount); .orElseThrow( () -> new Exception("Country " + country + " not supported"));

        – davidxxx
        7 hours ago











      • An IllegalArgumentException should be fine, but a plain Exception is a no-go...

        – Marco13
        6 hours ago















      13














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







      share|improve this answer




















      • 1





        This doesn't seem like a reasonable place to throw a checked exception. I know that OP's code does this, but I'd still rather not propagate it.

        – Ben P.
        8 hours ago






      • 4





        @BenP. I see no issue with throwing a checked exception if you receive an unexpected/not supported input. I'd probably use some custom exception and not the base Exception class though.

        – Eran
        8 hours ago











      • Or alternatively Optional.ofNullable(taxRateMap.get(country)) .mapping(taxRate -> new BigDecimal(taxRate).multiply(amount); .orElseThrow( () -> new Exception("Country " + country + " not supported"));

        – davidxxx
        7 hours ago











      • An IllegalArgumentException should be fine, but a plain Exception is a no-go...

        – Marco13
        6 hours ago













      13












      13








      13







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







      share|improve this answer















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








      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 8 hours ago

























      answered 8 hours ago









      EranEran

      299k37502581




      299k37502581







      • 1





        This doesn't seem like a reasonable place to throw a checked exception. I know that OP's code does this, but I'd still rather not propagate it.

        – Ben P.
        8 hours ago






      • 4





        @BenP. I see no issue with throwing a checked exception if you receive an unexpected/not supported input. I'd probably use some custom exception and not the base Exception class though.

        – Eran
        8 hours ago











      • Or alternatively Optional.ofNullable(taxRateMap.get(country)) .mapping(taxRate -> new BigDecimal(taxRate).multiply(amount); .orElseThrow( () -> new Exception("Country " + country + " not supported"));

        – davidxxx
        7 hours ago











      • An IllegalArgumentException should be fine, but a plain Exception is a no-go...

        – Marco13
        6 hours ago












      • 1





        This doesn't seem like a reasonable place to throw a checked exception. I know that OP's code does this, but I'd still rather not propagate it.

        – Ben P.
        8 hours ago






      • 4





        @BenP. I see no issue with throwing a checked exception if you receive an unexpected/not supported input. I'd probably use some custom exception and not the base Exception class though.

        – Eran
        8 hours ago











      • Or alternatively Optional.ofNullable(taxRateMap.get(country)) .mapping(taxRate -> new BigDecimal(taxRate).multiply(amount); .orElseThrow( () -> new Exception("Country " + country + " not supported"));

        – davidxxx
        7 hours ago











      • An IllegalArgumentException should be fine, but a plain Exception is a no-go...

        – Marco13
        6 hours ago







      1




      1





      This doesn't seem like a reasonable place to throw a checked exception. I know that OP's code does this, but I'd still rather not propagate it.

      – Ben P.
      8 hours ago





      This doesn't seem like a reasonable place to throw a checked exception. I know that OP's code does this, but I'd still rather not propagate it.

      – Ben P.
      8 hours ago




      4




      4





      @BenP. I see no issue with throwing a checked exception if you receive an unexpected/not supported input. I'd probably use some custom exception and not the base Exception class though.

      – Eran
      8 hours ago





      @BenP. I see no issue with throwing a checked exception if you receive an unexpected/not supported input. I'd probably use some custom exception and not the base Exception class though.

      – Eran
      8 hours ago













      Or alternatively Optional.ofNullable(taxRateMap.get(country)) .mapping(taxRate -> new BigDecimal(taxRate).multiply(amount); .orElseThrow( () -> new Exception("Country " + country + " not supported"));

      – davidxxx
      7 hours ago





      Or alternatively Optional.ofNullable(taxRateMap.get(country)) .mapping(taxRate -> new BigDecimal(taxRate).multiply(amount); .orElseThrow( () -> new Exception("Country " + country + " not supported"));

      – davidxxx
      7 hours ago













      An IllegalArgumentException should be fine, but a plain Exception is a no-go...

      – Marco13
      6 hours ago





      An IllegalArgumentException should be fine, but a plain Exception is a no-go...

      – Marco13
      6 hours ago













      5














      Put the data in an XML file or database, then use it to populate a dictionary. That way you can change the data easily, and separate the data from your application logic. Or, just execute a SQL query in your method instead.






      share|improve this answer



























        5














        Put the data in an XML file or database, then use it to populate a dictionary. That way you can change the data easily, and separate the data from your application logic. Or, just execute a SQL query in your method instead.






        share|improve this answer

























          5












          5








          5







          Put the data in an XML file or database, then use it to populate a dictionary. That way you can change the data easily, and separate the data from your application logic. Or, just execute a SQL query in your method instead.






          share|improve this answer













          Put the data in an XML file or database, then use it to populate a dictionary. That way you can change the data easily, and separate the data from your application logic. Or, just execute a SQL query in your method instead.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 8 hours ago









          EJoshuaSEJoshuaS

          7,622103151




          7,622103151





















              1














              If the values are constant and are not meant to be changed regularly (which I doubt). I'd introduce a static metamodel using Enum:



              public enum CountryList 

              AUSTRIA(BigDecimal.valueOf(0.20)),
              CYPRUS(BigDecimal.valueOf(0.19)),
              POLAND(BigDecimal.valueOf(0.23));

              private final BigDecimal countryTax;

              CountryList(BigDecimal countryTax)
              this.countryTax = countryTax;


              public BigDecimal getCountryTax()
              return countryTax;


              public static BigDecimal countryTaxOf(String countryName)
              CountryList country = Arrays.stream(CountryList.values())
              .filter(c -> c.name().equalsIgnoreCase(countryName))
              .findAny()
              .orElseThrow(() -> new IllegalArgumentException("Country is not found in the dictionary: " + countryName));

              return country.getCountryTax();




              Then



              private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception 
              return CountryList.countryTaxOf(country).multiply(amount);



              It's readable, compile time safe, easily extendable with additional metadata per country and less boilerplate.






              share|improve this answer























              • Why the stream?

                – immibis
                27 mins ago















              1














              If the values are constant and are not meant to be changed regularly (which I doubt). I'd introduce a static metamodel using Enum:



              public enum CountryList 

              AUSTRIA(BigDecimal.valueOf(0.20)),
              CYPRUS(BigDecimal.valueOf(0.19)),
              POLAND(BigDecimal.valueOf(0.23));

              private final BigDecimal countryTax;

              CountryList(BigDecimal countryTax)
              this.countryTax = countryTax;


              public BigDecimal getCountryTax()
              return countryTax;


              public static BigDecimal countryTaxOf(String countryName)
              CountryList country = Arrays.stream(CountryList.values())
              .filter(c -> c.name().equalsIgnoreCase(countryName))
              .findAny()
              .orElseThrow(() -> new IllegalArgumentException("Country is not found in the dictionary: " + countryName));

              return country.getCountryTax();




              Then



              private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception 
              return CountryList.countryTaxOf(country).multiply(amount);



              It's readable, compile time safe, easily extendable with additional metadata per country and less boilerplate.






              share|improve this answer























              • Why the stream?

                – immibis
                27 mins ago













              1












              1








              1







              If the values are constant and are not meant to be changed regularly (which I doubt). I'd introduce a static metamodel using Enum:



              public enum CountryList 

              AUSTRIA(BigDecimal.valueOf(0.20)),
              CYPRUS(BigDecimal.valueOf(0.19)),
              POLAND(BigDecimal.valueOf(0.23));

              private final BigDecimal countryTax;

              CountryList(BigDecimal countryTax)
              this.countryTax = countryTax;


              public BigDecimal getCountryTax()
              return countryTax;


              public static BigDecimal countryTaxOf(String countryName)
              CountryList country = Arrays.stream(CountryList.values())
              .filter(c -> c.name().equalsIgnoreCase(countryName))
              .findAny()
              .orElseThrow(() -> new IllegalArgumentException("Country is not found in the dictionary: " + countryName));

              return country.getCountryTax();




              Then



              private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception 
              return CountryList.countryTaxOf(country).multiply(amount);



              It's readable, compile time safe, easily extendable with additional metadata per country and less boilerplate.






              share|improve this answer













              If the values are constant and are not meant to be changed regularly (which I doubt). I'd introduce a static metamodel using Enum:



              public enum CountryList 

              AUSTRIA(BigDecimal.valueOf(0.20)),
              CYPRUS(BigDecimal.valueOf(0.19)),
              POLAND(BigDecimal.valueOf(0.23));

              private final BigDecimal countryTax;

              CountryList(BigDecimal countryTax)
              this.countryTax = countryTax;


              public BigDecimal getCountryTax()
              return countryTax;


              public static BigDecimal countryTaxOf(String countryName)
              CountryList country = Arrays.stream(CountryList.values())
              .filter(c -> c.name().equalsIgnoreCase(countryName))
              .findAny()
              .orElseThrow(() -> new IllegalArgumentException("Country is not found in the dictionary: " + countryName));

              return country.getCountryTax();




              Then



              private BigDecimal calculateTax(String country, BigDecimal amount) throws Exception 
              return CountryList.countryTaxOf(country).multiply(amount);



              It's readable, compile time safe, easily extendable with additional metadata per country and less boilerplate.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 7 hours ago









              Mikhail KholodkovMikhail Kholodkov

              6,18563154




              6,18563154












              • Why the stream?

                – immibis
                27 mins ago

















              • Why the stream?

                – immibis
                27 mins ago
















              Why the stream?

              – immibis
              27 mins ago





              Why the stream?

              – immibis
              27 mins ago











              0














              You may consider creating two arrays. It is easy to implement. For instance, in this case you may use :
              String[] countries = "Poland", "India", "Mexico",....;
              And another array for the respective BigDecimalvalue.
              BigDecimal[] taxrates = 0.23,0.5,0.75;
              Notice that since both the arrays are parallel, the value of index for both the arrays would be same for whichever is selected. For instance, index = 1 would always point to India and 0.5.
              In case you need to remove or add an element from the array, you can use a temporary array and copy the values. Then create a new array and copy the required values. You can also edit values using index like using SQL id. In case of dynamic and drastic changes I suggest using ArrayList where we can easily access get() and indexOf("") or remove("") methods.
              There maybe better approaches but I personally find this easy to implement.
              P.S. - Hashmap may also be used to solve the problem.






              share|improve this answer



























                0














                You may consider creating two arrays. It is easy to implement. For instance, in this case you may use :
                String[] countries = "Poland", "India", "Mexico",....;
                And another array for the respective BigDecimalvalue.
                BigDecimal[] taxrates = 0.23,0.5,0.75;
                Notice that since both the arrays are parallel, the value of index for both the arrays would be same for whichever is selected. For instance, index = 1 would always point to India and 0.5.
                In case you need to remove or add an element from the array, you can use a temporary array and copy the values. Then create a new array and copy the required values. You can also edit values using index like using SQL id. In case of dynamic and drastic changes I suggest using ArrayList where we can easily access get() and indexOf("") or remove("") methods.
                There maybe better approaches but I personally find this easy to implement.
                P.S. - Hashmap may also be used to solve the problem.






                share|improve this answer

























                  0












                  0








                  0







                  You may consider creating two arrays. It is easy to implement. For instance, in this case you may use :
                  String[] countries = "Poland", "India", "Mexico",....;
                  And another array for the respective BigDecimalvalue.
                  BigDecimal[] taxrates = 0.23,0.5,0.75;
                  Notice that since both the arrays are parallel, the value of index for both the arrays would be same for whichever is selected. For instance, index = 1 would always point to India and 0.5.
                  In case you need to remove or add an element from the array, you can use a temporary array and copy the values. Then create a new array and copy the required values. You can also edit values using index like using SQL id. In case of dynamic and drastic changes I suggest using ArrayList where we can easily access get() and indexOf("") or remove("") methods.
                  There maybe better approaches but I personally find this easy to implement.
                  P.S. - Hashmap may also be used to solve the problem.






                  share|improve this answer













                  You may consider creating two arrays. It is easy to implement. For instance, in this case you may use :
                  String[] countries = "Poland", "India", "Mexico",....;
                  And another array for the respective BigDecimalvalue.
                  BigDecimal[] taxrates = 0.23,0.5,0.75;
                  Notice that since both the arrays are parallel, the value of index for both the arrays would be same for whichever is selected. For instance, index = 1 would always point to India and 0.5.
                  In case you need to remove or add an element from the array, you can use a temporary array and copy the values. Then create a new array and copy the required values. You can also edit values using index like using SQL id. In case of dynamic and drastic changes I suggest using ArrayList where we can easily access get() and indexOf("") or remove("") methods.
                  There maybe better approaches but I personally find this easy to implement.
                  P.S. - Hashmap may also be used to solve the problem.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 8 hours ago









                  HeisenbergHeisenberg

                  133




                  133



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56586432%2fhow-can-i-improve-readability-and-length-of-a-method-with-many-if-statements%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її