How to clean your PHP code
/ PHP變量
PHP變量
變量
10. 合理使用參數(shù)默認值,沒必要在方法里再做默認值檢測
1. 使用見字知意的變量名
壞:
$ymdstr = $moment->format('y-m-d');
好:
$currentDate = $moment->format('y-m-d');
2. 同一個實體要用相同的變量名
壞:
getUserInfo(); getUserData(); getUserRecord(); getUserProfile();
好:
getUser();
3. 使用便于搜索的名稱 (part 1)
寫代碼是用來讀的。所以寫出可讀性高、便于搜索的代碼至關(guān)重要。 命名變量時如果沒有有意義、不好理解,那就是在傷害讀者。 請讓你的代碼便于搜索。
壞:
// 448 ? 干啥的? $result = $serializer->serialize($data, 448);
好:
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
4. 使用便于搜索的名稱 (part 2)
壞:
class User { // 7 ? 干啥的? public $access = 7; } // 4 ? 干啥的? if ($user->access & 4) { // ... } // 這里會發(fā)生什么? $user->access ^= 2;
好:
class User { const ACCESS_READ = 1; const ACCESS_CREATE = 2; const ACCESS_UPDATE = 4; const ACCESS_DELETE = 8; // 默認情況下用戶 具有讀、寫和更新權(quán)限 public $access = self::ACCESS_READ | self::ACCESS_CREATE | self::ACCESS_UPDATE; } if ($user->access & User::ACCESS_UPDATE) { // do edit ... } // 禁用創(chuàng)建權(quán)限 $user->access ^= User::ACCESS_CREATE;
5. 使用自解釋型變量
壞:
$address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches[1], $matches[2]);
不錯:
好一些,但強依賴于正則表達式的熟悉程度
$address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); [, $city, $zipCode] = $matches; saveCityZipCode($city, $zipCode);
好:
使用帶名字的子規(guī)則,不用懂正則也能看的懂
$address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches['city'], $matches['zipCode']);
6. 避免深層嵌套,盡早返回 (part 1)
太多的if else
語句通常會導致你的代碼難以閱讀,直白優(yōu)于隱晦
糟糕:
if (empty($day)) { return false; } $openingDays = [ 'friday', 'saturday', 'sunday' ]; return in_array(strtolower($day), $openingDays, true); }
7. 避免深層嵌套,盡早返回 (part 2)
糟糕的:
function fibonacci(int $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'; } }
好:
function fibonacci(int $n): int { if ($n === 0 || $n === 1) { return $n; } if ($n >= 50) { throw new \Exception('Not supported'); } return fibonacci($n - 1) + fibonacci($n - 2); }
8. 少用無意義的變量名
別讓讀你的代碼的人猜你寫的變量是什么意思。 寫清楚好過模糊不清。
壞:
$l = ['Austin', 'New York', 'San Francisco']; for ($i = 0; $i < count($l); $i++) { $li = $l[$i]; doStuff(); doSomeOtherStuff(); // ... // ... // ... // 等等, `$li` 又代表什么? dispatch($li); }
好:
$locations = ['Austin', 'New York', 'San Francisco']; foreach ($locations as $location) { doStuff(); doSomeOtherStuff(); // ... // ... // ... dispatch($location); }
9. 不要添加不必要上下文
如果從你的類名、對象名已經(jīng)可以得知一些信息,就別再在變量名里重復。
壞:
class Car { public $carMake; public $carModel; public $carColor; //... }
好:
class Car { public $make; public $model; public $color; //... }
10. 合理使用參數(shù)默認值,沒必要在方法里再做默認值檢測
不好:
不好,$breweryName
可能為 NULL.
function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void { // ... }
還行:
比上一個好理解一些,但最好能控制變量的值
function createMicrobrewery($name = null): void { $breweryName = $name ?: 'Hipster Brew Co.'; // ... }
好:
如果你的程序只支持 PHP 7+, 那你可以用 type hinting 保證變量 $breweryName
不是 NULL.
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void { // ... }