1.业务场景
在业务场景中,经常会出现很复杂的if else嵌套,譬如下面这种情况:👇👇👇
text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 请按你的实际需求修改参数
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进行优化呢?
2.优化代码
我在这里给出两种优化方式:①采用枚举实现;②采用Map实现。
text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
*
*/
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;
}
}
text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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"));
}
}
