首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Php:如何降低方法的复杂度

Php:如何降低方法的复杂度
EN

Code Review用户
提问于 2019-03-07 12:45:58
回答 1查看 133关注 0票数 0

我在检查器上将此方法评定为B级(直接链接:https://scrutinizer-ci.com/g/sineverba/domotic-panel/inspections/76996c9f-543f-43b4-9475-c64fe810a278/code-structure/operation/App%5CHttp%5CControllers%5CApi%5CPublicIpController%3A%3Aupdate)

代码语言:javascript
复制
public function update()
{
    try {
        $data = array();
        $update = false;
        $string_previous_public_ip = null;
        $current_public_ip = $this->getGateway()->fetchPublicIp($this->getIp());
        $previous_public_ip = $this->getGateway()->getLastRecord();
        $data[ 'ip_address' ] = $current_public_ip;
        if (isset($previous_public_ip->ip_address)) {
            $string_previous_public_ip = $previous_public_ip->ip_address;
            $data[ 'id' ] = $previous_public_ip->id;
        }
        if ($current_public_ip != $string_previous_public_ip) {
            $update = $this->updateOrCreate($data);
        }
        return response()->json([
            'updated' => $update
        ], 200);
    } catch (ConnectionError $e) {
        // Will return error 500
    } catch (ServiceError $e) {
        // Will return error 500
    } catch (\Exception $e) {
        // Will return error 500
    }
    return response()->json([
        'updated' => $update
    ], 500);
}

我能降低圈复杂度吗?我确实为更新移动了一个if/else (我认为这是他的工作很明显的updateOrCreate方法),但这还不够。

谢谢!

EN

回答 1

Code Review用户

回答已采纳

发布于 2019-03-07 14:00:26

你的三个catch街区和两个returns做的事情是一样的。你只需要每个人一个。

$update是在try之外引用的,也应该在那里定义。

$current_public_ip只是$data[ 'ip_address' ]的另一个名字。它既不短,也不清楚,也不太像它的另一个名字。

$previous_public_ip不是IP地址,而是包含IP地址和其他东西的对象。简单地将其命名为$previous会更清楚,它允许您从$string_previous_public_ip中删除冗余的string__public也可以去。

代码语言:javascript
复制
public function update()
{
    $update = false;
    $status = 500; // default
    try {
        $data = array();
        $previous_ip = null;
        $data[ 'ip_address' ] = $this->getGateway()->fetchPublicIp($this->getIp());
        $previous = $this->getGateway()->getLastRecord();
        if ( isset($previous->ip_address) ) {
            $previous_ip = $previous->ip_address;
            $data[ 'id' ] = $previous->id;
        }
        if ( $data[ 'ip_address' ] != $previous_ip ) {
            $update = $this->updateOrCreate($data);
        }
        $status = 200;
    } catch ( \Exception $e ) {
        // return default status (500)
    }
    return response()->json([ 'updated' => $update ], $status);
}
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

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

复制
相关文章

相似问题

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