5.不要使用标志做函数参数
标志相当于告诉使用者,这个函数不止做一件事。函数应该只做一件事,如果函数根据布尔值执行不同代码路径,则你应该将函数拆分。
不好的:
function createFile($name, $temp = false)
{
if ($temp) {
touch('./temp/'.$name);
} else {
touch($name);
}
}好的:
function createFile($name)
{
touch($name);
}
function createTempFile($name)
{
touch('./temp/'.$name);
}一个函数只做一件事
这是软件工程中最重要的原则。
不好的:
function emailClients($clients)
{
foreach ($clients as $client) {
$clientRecord = $db->find($client);
if ($clientRecord->isActive()) {
email($client);
}
}
}好的
function emailClients($clients)
{
$activeClients = activeClients($clients);
array_walk($activeClients, 'email');
}
function activeClients($clients)
{
return array_filter($clients, 'isClientActive');
}
function isClientActive($client)
{
$clientRecord = $db->find($client);
return $clientRecord->isActive();
}函数名要能说明它是做什么的
不好的:
class Email
{
//...
public function handle()
{
mail($this->to, $this->subject, $this->body);
}
}
$message = new Email(...);
// 这是什么?一条消息的句柄? 你是要写一个文件么?(读者的疑问)
$message->handle();好的
class Email
{
//...
public function send()
{
mail($this->to, $this->subject, $this->body);
}
}
$message = new Email(...);
// 一目了然
$message->send();