LoginSignup
1
1

More than 3 years have passed since last update.

変数と関数のネーミング

Posted at

変数・関数のネーミング

今更ですが変数・関数のネーミングについてリーダブルコードを元にまとめました。
上から順番に重要だと感じている順です。

リーダブルコード 4 章

一貫性

「同じデータ」は同じ変数名にしましょう。
(プロジェクト単位で良いです)

// a.php
$studentname = 'yamada';
// b.php
$username = 'tanaka';

↓↓↓

// a.php
$studentname = 'yamada';
// b.php
$studentname = 'tanaka';

リーダブルコード 8 章

説明変数

「処理」(の結果)を説明する変数

if (substr($str, 0, strcspn($str,'(')) === 'root') {... }

// ↓↓↓

$username = substr($str, 0, strcspn($str,'('))
if ($username === 'root') {... }

要約変数

状態とか、式を端的に説明する変数


if ($user->plan === 'gold') {... }

// ↓↓↓

$isGoldPlan = $user->plan === 'gold';
if ($isGoldPlan) {... }

リーダブルコード 3 章

誤解されない変数名

ニアイコール、とにかく詳しく書いてね

リーダブルコード 9 章

変数のスコープを考慮した名前にしましょう!

こんなクラスがあったとして、

class User
{
    private $id;

    function getUserId()
    {
        return $this->id;
    }
}

getUserId は、使われるときに冗長に見える

// user と UserId で user がかぶっている
$user->getUserId();

↓↓↓

// 関数に user がなくても、user id ってだいたい分かる
$user->getId();

ただし!!!

変数に入れるときはきちんと説明を入れて上げる必要がある。

// (id はきっと order.id とか、 admin.id とかいろいろあるから)
$userid  = $user->getId();
$orderid = $order->getId();

定数名

定数名が適当だと..

define('STATUS', 20);

ユーザーのステータス? 注文のステータス? 管理者のステータス?
↓↓↓

define('USER_STATUS', 20);

定数はより詳細な名前にしましょう!

その他

変数で説明するより、関数で説明したほうがわかりやすい(完結)です

$isGoldPlan = $user->plan === GOLD_PLAN;
if ($isGoldPlan) {... }

if ($user->isGoldPlan()) {... }

if ($user->isPlan(GOLD_PLAN)) {... }
1
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
1
1