PHP代碼簡潔之道——變量部分

將代碼寫的簡潔而且易讀易懂是每一位優秀的coder所應該具有的基本功。php

前幾天在github上看到clean-code-php這個項目,感受頗有收穫,因而在這裏記錄一下。git

使用有意義而且可讀的變量名稱

Bad:github

$ymdstr = $moment->format('y-m-d');

Good:函數

$currentDate = $moment->format('y-m-d');

對同一只類型的變量使用一樣的詞彙

Bad:spa

getUserInfo();
getUserData();
getUserRecord();
getUserProfile();

Good:code

getUser();

使用易於查找的命名

Bad:orm

// 這裏的4是什麼鬼??
if ($user->access & 4) {
    // ...
}

Good:對象

class User
{
    const ACCESS_READ = 1;
    const ACCESS_CREATE = 2;
    const ACCESS_UPDATE = 4;
    const ACCESS_DELETE = 8;
}

if ($user->access & User::ACCESS_UPDATE) {
    // do edit ...
}

不要讓讀者猜

Bad:ci

$l = ['Austin', 'New York', 'San Francisco'];

for ($i = 0; $i < count($l); $i++) {
    $li = $l[$i];
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    // $li 變量表明什麼???
    dispatch($li);
}

Good:get

$locations = ['Austin', 'New York', 'San Francisco'];

foreach ($locations as $location) {
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    dispatch($location);
}

避免過深的嵌套

Bad:

function isShopOpen($day)
{
    if ($day) {
        if (is_string($day)) {
            $day = strtolower($day);
            if ($day === 'friday') {
                return true;
            } elseif ($day === 'saturday') {
                return true;
            } elseif ($day === 'sunday') {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Good:

function isShopOpen($day)
{
    if (empty($day) && ! is_string($day)) {
        return false;
    }

    $openingDays = [
        'friday', 'saturday', 'sunday'
    ];

    return in_array(strtolower($day), $openingDays);
}

Bad:

function fibonacci($n)
{
    if ($n < 50) {
        if ($n !== 0) {
            if ($n !== 1) {
                return fibonacci($n - 1) + fibonacci($n - 2);
            } else {
                return 1;
            }
        } else {
            return 0;
        }
    } else {
        return 'Not supported';
    }
}

Good:

function fibonacci($n)
{
    if ($n === 0) {
        return 0;
    }

    if ($n === 1) {
        return 1;
    }

    if ($n > 50) {
        return 'Not supported';
    }

    return fibonacci($n - 1) + fibonacci($n - 2);
}

不要添加沒必要要的上下文

若是你的類/對象已經說明了一些信息,不要在你的變量名和屬性裏重複

Bad:

class Car
{
    public $carMake;
    public $carModel;
    public $carColor;

    //...
}

Good:

class Car
{
    public $make;
    public $model;
    public $color;

    //...
}

參數初始化時設置默認值

function create($name = null)
{
    $newName = $name ?: 'ABC';
    // ...
}

設置默認值一個比較明顯的好處是,當對一個較早以前已經定義好的函數添加參數時,將新增的參數設置默認值能夠免得去修改之前使用該函數的地方。

相關文章
相關標籤/搜索