首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在一个函数中优化嵌套的“if”集?

如何在一个函数中优化嵌套的“if”集?
EN

Code Review用户
提问于 2018-04-19 07:01:39
回答 1查看 82关注 0票数 3

我有这样一部分的职能:

代码语言:javascript
复制
$token = $this->getToken($user);

    if ('main' !== session('type') && is_null($token)) {
        $instagramProfile = $this->findInstagramProfile($user);
        $token = $instagramProfile->profile->user->api_token ?? null;
    } else {
        if (!$instagramProfile = $this->findInstagramProfile($user)) {
            $profile = create_instagram_profile($user);
            $user = $this->createUser($profile);
            $token = $user->api_token;
        } else {
            if($instagramProfile->profile->user) {
                $token = $instagramProfile->profile->user->api_token;
            } else {
                $user = $this->createUser($instagramProfile->profile);
                $token = $user->api_token;
            }
        };
    }

我有很多种情景:

  1. 在会话中保存的param type
  2. instagram剖面存在;
  3. 用户存在。

在世界上-非常简单,但在代码中,它是不可理解的。

我如何优化这部分代码?

也许能创造出更抽象的功能?

EN

回答 1

Code Review用户

回答已采纳

发布于 2018-04-19 07:35:36

我不知道该怎么做

代码语言:javascript
复制
    if ('main' !== session('type') && is_null($token)) {
        $instagramProfile = $this->findInstagramProfile($user);
        $token = $instagramProfile->profile->user->api_token ?? null;
    }

如果$instagramProfile->profile->user碰巧是null的话。否则,重构是非常简单的。只需一个接一个地将常见的操作从if/else中删除:

代码语言:javascript
复制
    $instagramProfile = this->findInstagramProfile($user);

    if (!$instagramProfile) {
        $instagramProfile = create_instagram_profile($user);
    }   

    user = $instagramProfile->profile->user;
    if (!user) {
        $user = $this->createUser($instagramProfile->profile);
    }

    $token = $user->api_token;

注意到这只是一次机械重写。

PS:我认为create_instagram_profile可以通过null参数安全地调用;无论如何,您都在这样做。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/192435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档