Java alternative of bad looking if-else or switch constructions

  • A+
Category:Languages

Looking for modern way to realise String translation to replace bad looking if-else or switch constructions:

if ("UK".equals(country))       name = "United Kingdom";   if ("GE".equals(country))      name = "Germany";   if ("FR".equals(country))      name = "France";   if ("IT".equals(country))      name = "Italy";   [...] 

or

switch (country) {       case "UK": name = "United Kingdom"; break;       case "GE": name = "Germany" break;       case "FR": name = "France"; break;       case "IT": name = "Italy" break;   [...] 

 


You might want an enum.

public enum Country {     UK("United Kingdom"),     GE("Germany"), // sure this isn't DE?     FR("France");     // and so on     private String countryName;     private Country(String n) { countryName = n; }      public String getCountryName() { return countryName; } } 

Now you can

Country c = Country.valueOf(countryString); // throws exception when unknown name = c.getCountryName(); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: