删除 else
如:
function test($arg)
{
if($arg == 'foobar'){
return true;
}else{
return false;
}
}
尽量写成这样
function test($arg)
{
if($arg == 'foobar'){
return true;
}
return false;
}
优先将代码量少,可使流程中断的代码块(return, throw excetion, continue ...)放到 if 中, 提前中断代码。
罗列规则式的写代码
多层 if 嵌套的语法,把他写成线性的,就像写规则一样将其一条条罗列出来
如:
function match($age, $salary, $pretty){ if($age > 18){ // do some thing A; if($salary > 5000){ // do some thing B; if($pretty == true){ return true; } } } return false; }改写成这样是不是清晰多了?
function match($age, $salary, $pretty){ if($age < 18){ return false; } // do some thing A; if($salary < 5000){ return false; } // do some thing B; return $pretty == true; }
function contry_initial($country){ if ($country==="China" ){ return "CHN"; }else if($country==="America"){ return "USA"; }else if($country==="Japna"){ return "JPN"; }else{ return "OTHER"; } }这样的if语句,可以看到值和返回是一一对应的,所以你可以这样写
function contry_initial($country){ $countryList=[ "China"=> "CHN", "America"=> "USA", "Japna"=> "JPN", ]; if(in_array($country, array_keys($countryList))) { return $countryList[$country]; } return "Other"; }如果需要更加自由的定义映射表的话,可以这样写
function contry_initial($country, array $countryList){ if(in_array($country, array_keys($countryList))) { return $countryList[$country]; } return "Other"; }完全去掉if语句可以写成
function contry_initial($country, array $countryList){ return in_array($country, array_keys($countryList))?$countryList[$country]:"Other"; }
https://laravel-china.org/topics/1284/if-else-reconstruction-experience
https://laravel-china.org/topics/1263/tips-to-make-your-if-else-look-more-beautiful
本文介绍如何通过重构简化复杂的if-else语句,包括减少嵌套、使用映射表替代多个条件判断等技巧,提高代码可读性和维护性。
628

被折叠的 条评论
为什么被折叠?



