一. 使用Map优化if-else if结构
优化后的代码
final Map<String, String> stateMap = ImmutableMap.<String, String>builder()
.put("0", StringUtils.isBlank("内容零")?"":"内容零")
.put("1", StringUtils.isBlank("内容一")?"":"内容一")
.put("2", StringUtils.isBlank("内容二")?"":"内容二")
.put("3", StringUtils.isBlank("内容三")?"":"内容三")
.put("4", StringUtils.isBlank("内容四")?"":"内容四")
.put("5", StringUtils.isBlank("内容五")?"":"内容五")
.put("6", StringUtils.isBlank("内容六")?"":"内容六")
.put("7", StringUtils.isBlank("内容七")?"":"内容七")
.put("8", StringUtils.isBlank("内容八")?"":"内容八")
.put("9", StringUtils.isBlank("内容九")?"":"内容九")
.build();
String isAbnormalStr = stateMap.get("7");
System.out.println(isAbnormalStr);
这种方法只是针对if-else比较多的情况
如果value值是固定的,并且想抽出来形成一个公共类,在final前面加上 public static
代码中使用到了一个ImmutableMap的东西,这是Google里的一个类,可生成一个不可变的Map对象,这就意味着,初始化定义后,后续就无法再put修改了,它的这个特性可以保证线程的安全。一般用来替换if-else的map,我们就是要求在初始化定义后,就不会再允许修改了,因此,这个ImmutableMap生成的map,可以很好地帮我们实现这一点。另外,最重要一点是,使用这个ImmutableMap,可以实现链式编程,就像上面定义的链式写法,若是用传统的map定义,就每次都要map.put()赋值。
优化之前的代码示例
if ("0".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", gfMap.get(isAbnormal));
}
} else if ("1".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", wsMap.get(isAbnormal));
}
} else if ("2".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", sdMap.get(isAbnormal));
}
} else if ("3".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", imgMap.get(isAbnormal));
}
} else if ("4".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", hbMap.get(isAbnormal));
}
} else if ("5".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", vrMap.get(isAbnormal));
}
} else if ("6".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", sfMap.get(isAbnormal));
}
} else if ("7".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", mbMap.get(isAbnormal));
}
} else if ("8".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", avMap.get(isAbnormal));
}
} else if ("9".equals(deviceRole)) {
if (StringUtils.isNotBlank(isAbnormal)) {
data.put("isAbnormalStr", biMap.get(isAbnormal));
}
}
相比于优化后的,这种多重if-else if代码非常的冗余,可读性也非常的低
二. 使用Optional类优化多重if-else嵌套结构
Optional 类是jdk1.8的新特性,可以用来优化多种if嵌套的情况,优化后的效果如下
优化之前的代码示例
这种情况主要针对于下面这种情况,如果其中某个属性值为null,就会抛出空指针异常
String village = province.getCity().getArea().getVillage();
如果用传统写法解决这种异常,就会用到大量的if
String village = null;
if(province != null){
City city = province.getCity();
if(city != null){
Area area = city.getArea();
if(area != null){
village = area.getVillage();
}
}
}
优化后的代码
String village = Optional.ofNullable(province)
.flatMap(Province::getCity)
.flatMap(City::getArea)
.map(Area::getVillage)
.orElse(null);