场景1:equals判断
int code;
if("Name".equals(str))
code = 0;
else if("Age".equals(str))
code = 1;
else if("Address".equals(str))
code = 2;
...
可以用Map进行优化:
Map typeCodeMap = new HashMap();
typeCodeMap.put("Name", 0);
typeCodeMap.put("Age", 1);
typeCodeMap.put("Address", 2);
...
int code = typeCode.get(type);
场景2: 判断多个变量是否为空
if (StringUtils.isBlank(a)) {
response.setSuccess(false);
response.setMessage("a can not be null");
} else if (StringUtils.isBlank(b)) {
response.setSuccess(false);
response.setMessage("b can not be null");
} else if (StringUtils.isBlank(c)) {
response.setSuccess(false);
response.setMessage("c can not be null");
} else if (StringUtils.isBlank(d)) {
response.setSuccess(false);
response.setMessage("d can not be null");
} else if (StringUtils.isBlank(e)) {
response.setSuccess(false);
response.setMessage("e can not be null");
}
用Map进行优化:
Map<String, String> paramMap = new HashMap<>(5);
paramMap.put("a", a);
paramMap.put("b", b);
paramMap.put("c", c);
paramMap.put("d", d);
paramMap.put("e", e);
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
if (StringUtils.isBlank(entry.getValue())) {
response.setSuccess(false);
response.setMessage(entry.getKey() + " can not be null");
return response;
}
}