在代碼調試過程中,往往需要花費大量的精力處理業務邏輯。我們先來看一個業務需求
- 實現一個遠程調用接口,修改指定網絡接口的IP地址,子網掩碼,默認網關。
- 需要同步修改/etc/network/interface文件。
- 接口傳入參數為json結構。
部分同學會這樣實現:
int set_net_work(cJSON *param)
{
if(param != NULL){
const char *eth = cJSON_GetObjectItem(param,"eth");
if(eth != NULL){
const char *ipaddr = cJSON_GetObjecItem(param,"ipaddr");
if(ipaddr != NULL){
if(eth == eth1){ //strcmp!!!!
read_file_get_params(eth1) //讀取配置文件獲取原始ip地址等信息
change_ipaddr(eth1); //修改ip地址
restore_gwaddr(eth1); //重新保存網關地址
....
}else if(eth = eth2){ //strcmp!!!!
....
}
}
if(gwaddr != NULL){
...
}
.....
}else{
return -1;
}
}else{
return -1;
}
}
上面的代碼實現的并不好,邏輯嵌套太深,可讀性較低。
其實業務邏輯大致可分為三個處理步驟,參數校驗,參數準備,根據參數處理業務。我們根據這三個步驟來處理一下上面的代碼
參數校驗
參數校驗,即檢測參數的合法性。代碼如下:
int set_net_work(cJSON *param)
{
if(param == NULL)
return -1;
const char *eth = cJSON_GetObjectItem(param,"eth");
if(eth == NULL)
return -1;
....
}
參數準備
即準備參數,包括從傳入參數獲得,或由于業務邏輯,執行一些其他準備工作。
int set_net_work(cJSON *param)
{
//參數校驗
if(param == NULL)
return -1;
const char *eth = cJSON_GetObjectItem(param,"eth");
if(eth == NULL)
return -1;
//參數準備
cJSON *ipaddr == cJSON_GetObjectItem(param,"ipaddr");
cJSON *netmask == cJSON_GetObjectItem(param,"netmask");
cJSON *defgw == cJSON_GetObjectItem(param,"defgw");
net_param = read_file_get_params(eth); //獲取指定網卡的參數
if(ipaddr == NULL) //如果沒有傳入ipaddr,則獲取原始信息
ipaddr = net_param.ipaddr;
if(netmask == NULL)
netmask = net_param.netmask;
if(defgw == NULL)
defgw = net_param.defgw;
}
業務邏輯處理
即執行業務邏輯動作,可單獨實現一個函數
int do_set_net_work(const char *eth,const char *ipaddr,const char *netmask,const char *defgw)
{
.... //業務邏輯處理。
}
//完整代碼
int set_net_work(cJSON *param)
{
//參數校驗
if(param == NULL)
return -1;
const char *eth = cJSON_GetObjectItem(param,"eth");
if(eth == NULL)
return -1;
//參數準備
cJSON *ipaddr == cJSON_GetObjectItem(param,"ipaddr");
cJSON *netmask == cJSON_GetObjectItem(param,"netmask");
cJSON *defgw == cJSON_GetObjectItem(param,"defgw");
net_param = read_file_get_params(eth); //獲取指定網卡的參數
if(ipaddr == NULL) //如果沒有傳入ipaddr,則獲取原始信息
ipaddr = net_param.ipaddr;
if(netmask == NULL)
netmask = net_param.netmask;
if(defgw == NULL)
defgw = net_param.defgw;
do_set_net_work(...);
}
總結:
業務邏輯代碼總是項目中邏輯最復雜的部分,實現的時候盡量少用if嵌套,可讀性會提高很多。