将代码写的简洁并且易读易懂是每一位优秀的coder所应该具备的基本功。
前几天在github上看到clean-code-php这个项目,感觉很有收获,于是在这里记录一下。
使用有意义并且可读的变量名称
Bad:
1
| $ymdstr = $moment->format('y-m-d');
|
Good:
1
| $currentDate = $moment->format('y-m-d');
|
对同一只类型的变量使用同样的词汇
Bad:
1 2 3 4
| getUserInfo(); getUserData(); getUserRecord(); getUserProfile();
|
Good:
使用易于查找的命名
Bad:
1 2 3 4
| if ($user->access & 4) { }
|
Good:
1 2 3 4 5 6 7 8 9 10 11
| class User { const ACCESS_READ = 1; const ACCESS_CREATE = 2; const ACCESS_UPDATE = 4; const ACCESS_DELETE = 8; }
if ($user->access & User::ACCESS_UPDATE) { }
|
不要让读者猜
Bad:
1 2 3 4 5 6 7 8 9 10 11 12
| $l = ['Austin', 'New York', 'San Francisco'];
for ($i = 0; $i < count($l); $i++) { $li = $l[$i]; doStuff(); doSomeOtherStuff(); dispatch($li); }
|
Good:
1 2 3 4 5 6 7 8 9 10
| $locations = ['Austin', 'New York', 'San Francisco'];
foreach ($locations as $location) { doStuff(); doSomeOtherStuff(); dispatch($location); }
|
避免过深的嵌套
Bad:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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:
1 2 3 4 5 6 7 8 9 10 11 12
| function isShopOpen($day) { if (empty($day) && ! is_string($day)) { return false; }
$openingDays = [ 'friday', 'saturday', 'sunday' ];
return in_array(strtolower($day), $openingDays); }
|
Bad:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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:
1 2 3 4 5 6 7 8
| class Car { public $carMake; public $carModel; public $carColor;
}
|
Good:
1 2 3 4 5 6 7 8
| class Car { public $make; public $model; public $color;
}
|
参数初始化时设置默认值
1 2 3 4 5
| function create($name = null) { $newName = $name ?: 'ABC'; }
|
设置默认值一个比较明显的好处是,当对一个较早之前已经定义好的函数添加参数时,将新增的参数设置默认值可以省得去修改以前使用该函数的地方。
参考链接