将代码写的简洁而且易读易懂是每一位优秀的coder所应该具有的基本功。php
前几天在github上看到clean-code-php这个项目,感受颇有收获,因而在这里记录一下。git
Bad:github
$ymdstr = $moment->format('y-m-d');
Good:函数
$currentDate = $moment->format('y-m-d');
Bad:spa
getUserInfo(); getUserData(); getUserRecord(); getUserProfile();
Good:code
getUser();
Bad:orm
// 这里的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:ci
$l = ['Austin', 'New York', 'San Francisco']; for ($i = 0; $i < count($l); $i++) { $li = $l[$i]; doStuff(); doSomeOtherStuff(); // ... // ... // ... // $li 变量表明什么??? dispatch($li); }
Good:get
$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'; // ... }
设置默认值一个比较明显的好处是,当对一个较早以前已经定义好的函数添加参数时,将新增的参数设置默认值能够免得去修改之前使用该函数的地方。