减少if-else使用

本文介绍如何通过重构简化复杂的if-else语句,包括减少嵌套、使用映射表替代多个条件判断等技巧,提高代码可读性和维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

删除 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值