网站首页 文章专栏 PHP版的代码整洁之道 变量篇
使用见字知意的变量名
坏:
$ymdstr = $moment->format('y-m-d');
好:
$currentDate = $moment->format('y-m-d');
同一个实体要用相同的变量名
坏:
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();
好:
getUser();
使用便于搜索的名称 (part 1)
写代码是用来读的。所以写出可读性高、便于搜索的代码至关重要。 命名变量时如果没有有意义、不好理解,那就是在伤害读者。 请让你的代码便于搜索。
坏:
// What the heck is 448 for?
$result = $serializer->serialize($data, 448);
好:
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
使用便于搜索的名称 (part 2)
坏:
// What the heck is 4 for?
if ($user->access & 4) {
// ...
}
好:
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 ...
}
使用自解释型变量
坏:
$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);
好:
使用带名字的子规则,不用懂正则也能看的懂
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(?.+?)\s*(?\d{5})$/' ;
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches['city'], $matches['zipCode']);
避免深层嵌套,尽早返回 (part 1)
太多的if else语句通常会导致你的代码难以阅读,直白优于隐晦
糟糕:
function isShopOpen($day): bool
{
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;
}
}
好:
function isShopOpen(string $day): bool
{
if (empty($day)) {
return false;
}
$openingDays = [
'friday', 'saturday', 'sunday'
];
return in_array(strtolower($day), $openingDays, true);
}
避免深层嵌套,尽早返回 (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);
}
少用无意义的变量名
别让读你的代码的人猜你写的变量是什么意思。 写清楚好过模糊不清。
坏:
$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);
}
不要添加不必要上下文
如果从你的类名、对象名已经可以得知一些信息,就别再在变量名里重复。
坏:
class Car
{
public $carMake;
public $carModel;
public $carColor;
//...
}
好:
class Car
{
public $make;
public $model;
public $color;
//...
}
合理使用参数默认值,没必要在方法里再做默认值检测
不好:
不好,$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 { // ... }
原文地址:https://github.com/php-cpm/clean-code-php#%E7%9B%AE%E5%BD%95