我在检查器上将此方法评定为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)
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方法),但这还不够。
谢谢!
发布于 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也可以去。
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);
}https://codereview.stackexchange.com/questions/214914
复制相似问题