使用有意义的并且可以读出来的变量名称
不好的:
$ymdstr = $moment->format('y-m-d');
好的:
$currentDate = $moment->format('y-m-d');
对于同一类型的变量使用相同的词汇
不好的:
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();
好的:
getUser();
(译者注:都是要取用户信息,不好的案例中为同一件事起了多个名字,在编码中是要避免的)
使用易于查找的名称(第一部分)
我们读代码的时候要比写代码的时候多的多,所以我们写的代码易读易查找是很重要的。如果不命名好对理解我们的程序有意义的变量,我们会伤害到读我们代码的人。确保你的变量易于查找。
不好的:
// 448 是什么鬼?
$result = $serializer->serialize($data, 448);
好的:
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
使用易查找的名称(第二部分)
不好的:
// 4 是什么鬼?
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);
list(, $city, $zipCode) = $matches;
saveCityZipCode($city, $zipCode);
好的:
通过使用命名子模式我们不必再依赖正则
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(?<city>.+?)\s*(?<zipCode>\d{5})?$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches['city'], $matches['zipCode']);
不要让读者猜
不要强迫你代码的读者去翻译变量的含义,显式比隐式要好
不好的:
$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.')
{
// ...
}
好一点的:
这个比上一个版本好一点,因为可以保证 $breweryName
不为 Null
function createMicrobrewery($name = null)
{
$breweryName = $name ?: 'Hipster Brew Co.';
// ...
}
好的:
如果你只需要支持 PHP 7
以上的版本, 你可以使用使用类型提示来保证 $breweryName
不为 NULL
。
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.')
{
// ...
}
本文翻译至:clean-code-php 的变量部分。
转载请注明:大后端 » PHP 代码简洁之道——变量部分