求助:一堆的if else 嵌套
private Map versionCheck(Map mapParam) {
Map msg = new HashMap();
if(!"".equals(PMSUtil.isNull(mapParam.get("IS_INTERNET")))){
String checkVersion =SystemGlobals.getProperty("IS_CHECK");
if("1".equals(checkVersion)){
String versions =SystemGlobals.getProperty("VERSION");
String version =PMSUtil.isNull(mapParam.get("VERSION"));
String taxRegisterNo=PMSUtil.isNull(mapParam.get(""));
String whiteList =SystemGlobals.getProperty("NO_CHECK_TAX_REGISTER_NO");
if((","+whiteList+",").indexOf((","+taxRegisterNo+","))==-1){
if((","+versions+",").indexOf(","+version+",")==-1){//找不到
msg.put("RESULT", "0001");
msg.put("MSG", "FAILD");
}else{
msg.put("RESULT", ""0000"");
}
}else{
msg.put("RESULT", ""0000"");
}
}else{
msg.put("RESULT", ""0000"");
}
}else{
msg.put("RESULT", ""0000"");
}
return msg;
}
ringa_lee2017-04-17 11:31:22
楼主就不要用你那山寨的 PMSUtil
了吧,直接上 org.apache.commons.lang.StringUtils
private Map versionCheck(Map mapParam) {
Map msg = new HashMap();
msg.put("RESULT", "0000");
String isInternet = (String) mapParam.get("IS_INTERNET");
if (StringUtils.isBlank(isInternet)) {
return msg;
}
String isCheck = SystemGlobals.getProperty("IS_CHECK");
if (!StringUtils.equals(isCheck, "1")) {
return msg;
}
String globalVersions = SystemGlobals.getProperty("VERSION");
String currentVersion = (String) mapParam.get("VERSION");
if (!StringUtils.contains("," + globalVersions + ",", "," + currentVersion + ",")) {
return msg;
}
String whiteList = SystemGlobals.getProperty("NO_CHECK_TAX_REGISTER_NO");
String taxRegisterNo = (String) mapParam.get("");
if (!StringUtils.contains("," + whiteList + ",", "," + taxRegisterNo + ",")) {
msg.put("RESULT", "0001");
msg.put("MSG", "FAILD");
return msg;
}
return Collections.emptyMap();
}
PHP中文网2017-04-17 11:31:22
1. 整体可简化为:
if () {
if () {
if () {
if () {
msg.put("RESULT", "0001");
msg.put("MSG", "FAILD");
return msg;
}
}
}
}
msg.put("RESULT", "0000");
return msg;
2. str.indexOf(s) == -1
可简化为 !str.contains(s)
3. 使用 2 之后,最里层的两个 if 语句:
if (c1) {
if (c2) {
...
}
}
可以写成:
if (c1 && c2) {
...
}
大家讲道理2017-04-17 11:31:22
按照逻辑整合,具体到这个例子中,可以将先设置默认值:
msg.put("RESULT", ""0000"");
然后再加上if语句,这样的话剩余后面一大堆的else语句就可以省略掉了。
黄舟2017-04-17 11:31:22
有几个建议
1. 尽量不要使用 else 而是尽早 retrun
void foo(){
if(bad){
//doSomthing
return ;
}
//else <- 这个就可以不写了
//real good logic;
}
if(s!= null && s.isValid() && s.then(doSomthing))
String result(String a){
return (checkVersion(a) || isInternet(a)) ? "OK" :"000-default";
}
boolean checkVersion(String ver){
return StringUtils.notBlank(ver) && ver.equals("...");
}
boolean isInternet(String ver){
return StringUtils.notBlank(ver) && ver.equals("internet");
}
void main(){
//...
someMap.put(result(String a));
//...
}
所有的逻辑应该尽量分拆成多而小的函数,这些没有副作用的函数可以被组装成复杂的逻辑而且不失可读性。但是这需要一定的经验。