2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHPのコードレビューこんなんやってる(その1)

Posted at

概要

意外とそんなにパターン無いのではと思い、整理と今後の備忘がてら記載してみました。実際にメンバーにしたレビュー内容をもとにしています。ちなみに思い立ったきっかけはこちらのツイート(X)でした。

※写真は全く関係ない

前提

以下の内容を踏まえてもらえるとひょっとしたら何かの参考になる度合いが

  • PHPです
  • 1年目にしたレビューが元になっています

レビュー内容

  • returnでなんか値返すfunctionなら、命名に「set◯◯」って付けるのは辞めたほうが良さそう
  • functionまるごとifの条件文で囲われてるから、条件を逆にして早期return
  • 片方の条件に引っかかったときにreturnしちゃっていい

returnでなんか値返すfunctionなら、命名に「set◯◯」って付けるのは辞めたほうが良さそう

class全体の中でfunctionがどういう役割なのかは一旦置いておいて、役割が想像できる命名にはしておきたいという内容ですね。

before

function setShopList()
{
    (何らかの処理)

    return $shopList;
}

after

function getShopList()
{
    (何らかの処理)

    return $shopList;
}

functionまるごとifの条件文で囲われてるから、条件を逆にして早期return

なんやかんやネストを浅くする心がけは要所でやっていますね。

before

function getCustomerAd($customer)
{
    if(!empty($customer['adId']) {
        ($customer['adId']でデータを取ってくる処理)
        return $adData;
    }

    return [];
}

after

function getCustomerAd($customer)
{
    if(empty($customer['adId']) {
        return [];
    }

    ($customer['adId']でデータを取ってくる処理)

    return $adData;
}

片方の条件に引っかかったときにreturnしちゃっていい

同上+返り値が確定した段階でreturnしてしまった方が、返り値も安定するよなあという気持ちで整理はよくしますね。

before

function getCustomerComment($customer)
{
    $comment = '';

    if(!empty($customer['staffId']) {
        ($customer['staffId']でスタッフコメントデータを取ってくる処理)
        $comment = $staffComment;
    } elseif ($customer['shopId']) {
        ($customer['shopId']で店舗コメントデータを取ってくる処理)
        $comment = $shopComment;
    }

    $comment;
}

after

function getCustomerComment($customer)
{
    if(!empty($customer['staffId']) {
        ($customer['staffId']でスタッフコメントデータを取ってくる処理)
        return $staffComment;
    }

    if ($customer['shopId']) {
        ($customer['shopId']で店舗コメントデータを取ってくる処理)
        return $shopComment;
    }

    return '';
}

終わり

まだまだあるような気もするし、そんなにパターンがないような気もします。
できれば単発企画にならないように、継続してけたらいいなあというところですね。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?