php 代码简洁之道,PHP代码简洁之道——变量部分

将代码写的简洁并且易读易懂是每一位优秀的coder所应该具备的基本功。

前几天在github上看到clean-code-php这个项目,感觉很有收获,于是在这里记录一下。

使用有意义并且可读的变量名称

Bad:

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

Good:

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

对同一只类型的变量使用同样的词汇

Bad:

getUserInfo();

getUserData();

getUserRecord();

getUserProfile();

Good:

getUser();

使用易于查找的命名

Bad:

// 这里的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:

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

for ($i = 0; $i < count($l); $i++) {

$li = $l[$i];

doStuff();

doSomeOtherStuff();

// ...

// ...

// ...

// $li 变量代表什么???

dispatch($li);

}

Good:

$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';

// ...

}

设置默认值一个比较明显的好处是,当对一个较早之前已经定义好的函数添加参数时,将新增的参数设置默认值可以省得去修改以前使用该函数的地方。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值