简化方法或函数中的 if else 代码

如果if中返回值时, 就不要在写 else

经常会看到这种写法:

if (...) {
  return false;
} else {
  return true;
}

如果if有返回值了,可以这样写:

if (...) {
  return false;
}

return true;
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 10
pndx

一样不喜欢else的路过

3年前 评论
playmaker (楼主) 3年前
windawake

为何不是跟汇编指令流水线来讲if else的正确用法?

3年前 评论
playmaker (楼主) 3年前

三元运算符 链接

3年前 评论
mouyong

用 LUT(look up table)

3年前 评论
playmaker (楼主) 3年前
mouyong (作者) 3年前
mouyong
public function process($type)
{
    $typeMap = [
        1 => 'processOne',
        2 => 'processTwo',
    ];

    if (! array_key_exists($type, $typeMap)) {
        throw new \LogicException("unknown type $type");
    }

    $method = $typeMap[$type];

    if (! method_exists($this, $method)) {
        throw new \LogicException(sprintf("unknown implement method $method in class %s", get_class($this)));
    }

    return $this->{$method}();
}
3年前 评论
$response = $result;
if(...){
    $response = $this->resolveResult($response);
}
return $response;
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!