共計 1172 個字符,預計需要花費 3 分鐘才能閱讀完成。
一、概述
當我們想提供可靠的 API 接口,對參數的校驗,以保證最終數據入庫的正確性,是 必不可少 的活。比如下圖就是 我們一個項目里 新增一個菜單校驗 參數的函數,寫了一大堆的 if else 進行校驗,非常的不優雅,比起枯燥的 CRUD 來說,參數校驗更是枯燥。這只是一個創建菜單的校驗,只需要判斷菜單,菜單 url 以及菜單的父類 id 是否為空,上級菜單是否掛載正確,這樣已經消耗掉了 30,40 行代碼了,更不要說,管理后臺創建商品這種參數賊多的接口。估計要寫幾百行校驗代碼了。
/**
* 驗證參數是否正確
*/
private void verifyForm(SysMenuEntity menu){if(StringUtils.isBlank(menu.getName())){throw new RRException(" 菜單名稱不能為空 ");
}
if(menu.getParentId() == null){throw new RRException(" 上級菜單不能為空 ");
}
// 菜單
if(menu.getType() == Constant.MenuType.MENU.getValue()){if(StringUtils.isBlank(menu.getUrl())){throw new RRException(" 菜單 URL 不能為空 ");
}
}
// 上級菜單類型
int parentType = Constant.MenuType.CATALOG.getValue();
if(menu.getParentId() != 0){SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
parentType = parentMenu.getType();}
// 目錄、菜單
if(menu.getType() == Constant.MenuType.CATALOG.getValue() ||
menu.getType() == Constant.MenuType.MENU.getValue()){if(parentType != Constant.MenuType.CATALOG.getValue()){throw new RRException(" 上級菜單只能為目錄類型 ");
}
return ;
}
// 按鈕
if(menu.getType() == Constant.MenuType.BUTTON.getValue()){if(parentType != Constant.MenuType.MENU.getValue()){throw new RRException(" 上級菜單只能為菜單類型 ");
}
return ;
}
}
正文完