1.业务场景 在业务场景中,经常会出现很复杂的if else嵌套,譬如下面这种情况: // 请按你的实际需求修改参数 public String convertCountryName(String fullName) { if ("china".equalsIgnoreCase(fullName))...
在业务场景中,经常会出现很复杂的if else嵌套,譬如下面这种情况:👇👇👇
// 请按你的实际需求修改参数
public String convertCountryName(String fullName) {
if ("china".equalsIgnoreCase(fullName)) {
return "CN";
} else if ("america".equalsIgnoreCase(fullName)) {
return "US";
} else if ("japan".equalsIgnoreCase(fullName)) {
return "JP";
} else if ("england".equalsIgnoreCase(fullName)) {
return "UK";
} else if ("france".equalsIgnoreCase(fullName)) {
return "FR";
} else if ("germany".equalsIgnoreCase(fullName)) {
return "DE";
} else {
throw new RuntimeException("unknown country");
}
}
对于上面的代码,可能我们大体上看还挺舒服的,可读性也不错。但是假设我们的业务需要支持地球上所有国家的名字与简写的转换,那么以目前的写法,将会出现有上百个if else,这样一来,代码的可读性、可扩展性等方面都将得不到一个好的保障。
所以我们能不能考虑对这上百个if-else进行优化呢?
<hr>
我在这里给出两种优化方式:①采用枚举实现;②采用Map实现。
/**
*
*/
public enum CountryEnum {
china("CN"),
america("US"),
japan("JP"),
england("UK"),
france("FR"),
germany("DE"),
;
private String fullName;
CountryEnum(String fullName) {
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
}
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class CountryNameConverter {
// 请按你的实际需求修改参数
public String convertCountryName(String fullName) {
if ("china".equalsIgnoreCase(fullName)) {
return "CN";
} else if ("america".equalsIgnoreCase(fullName)) {
return "US";
} else if ("japan".equalsIgnoreCase(fullName)) {
return "JP";
} else if ("england".equalsIgnoreCase(fullName)) {
return "UK";
} else if ("france".equalsIgnoreCase(fullName)) {
return "FR";
} else if ("germany".equalsIgnoreCase(fullName)) {
return "DE";
} else {
throw new RuntimeException("unknown country");
}
}
/**
* 优化方式一:定义相关枚举类
*/
public String chooseCountry(CountryEnum countryEnum) {
return countryEnum.getFullName();
}
public String getCountry(String fullName) {
return chooseCountry(CountryEnum.valueOf(fullName));
}
/**
* 优化方式二:将这些信息存入一个map集合中
*/
public Map<String, String> getCountryMap() {
Map<String, String> map = new HashMap<>();
map.put("china", "CN");
map.put("america", "US");
map.put("japan", "JP");
map.put("england", "UK");
map.put("france", "FR");
map.put("germany", "DE");
map.put("other", "unknown country");
return map;
}
public static void main(String[] args) {
//方式一测试
CountryNameConverter countryName = new CountryNameConverter();
System.out.println(countryName.getCountry("france"));
System.out.println(CountryEnum.china.getFullName());
//方式二测试
Map<String, String> countryMap = countryName.getCountryMap();
System.out.println(countryMap.get("england"));
}
}
本站为非盈利网站,如果您喜欢这篇文章,欢迎支持我们继续运营!
本站主要用于日常笔记的记录和生活日志。本站不保证所有内容信息可靠!(大多数文章属于搬运!)如有版权问题,请联系我立即删除:“abcdsjx@126.com”。
QQ: 1164453243
邮箱: abcdsjx@126.com