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

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

经常会看到这种写法:

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

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

if (...) {
  return false;
}

return true;
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 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年前 评论

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