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

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

经常会看到这种写法:

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

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

if (...) {
  return false;
}

return true;
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 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年前 评论

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