求助:一堆的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));
//...
}
所有的邏輯應該盡量分拆成多而小的函數,這些沒有副作用的函數可以被組裝成複雜的邏輯而且不失可讀性。但這需要一定的經驗。