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

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

经常会看到这种写法:

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

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

if (...) {
  return false;
}

return true;
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 10
pndx

一样不喜欢else的路过

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

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

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

三元运算符 链接

2年前 评论
mouyong

用 LUT(look up table)

2年前 评论
playmaker (楼主) 2年前
mouyong (作者) 2年前
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}();
}
2年前 评论
$response = $result;
if(...){
    $response = $this->resolveResult($response);
}
return $response;
2年前 评论

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