不添加不需要的上下文
如果你的類名或?qū)ο竺Q有具體的含義,請不要重復(fù)該變量的名稱。
差:
<?php class Car{ public $carMake; public $carModel; public $carColor; //... }
好:
<?php class Car{ public $make; public $model; public $color; //... }
函數(shù)參數(shù)數(shù)量(理想情況是 2 個以下)
限制函數(shù)參數(shù)的數(shù)量是非常重要的,因為它讓函數(shù)更容易測試,參數(shù)超過三個的話,你必須用每個單獨的參數(shù)測試大量不同的情況。
無參數(shù)是理想的情況。一個或兩個參數(shù)是可以的,但應(yīng)該避免三個。通常,如果你有兩個以上的參數(shù),那么你的函數(shù)試圖完成太多的功能,若不是,大多數(shù)時候,較高級的對象就足以作為參數(shù)(譯者注:比如數(shù)組、對象)。
差:
<?php function createMenu($title, $body, $buttonText, $cancellable) { // ...}
好:
<?php class MenuConfig { public $title; public $body; public $buttonText; public $cancellable = false;}$config = new MenuConfig();$config->title = 'Foo';$config->body = 'Bar';$config->buttonText = 'Baz';$config->cancellable = true;function createMenu(MenuConfig $config) { // ...}
一個函數(shù)應(yīng)該只完成一件事
這是軟件工程中最重要的規(guī)則。當(dāng)函數(shù)做的事多于一件事情時,他們更難編寫和測試。 當(dāng)你可以將函數(shù)隔離成一個動作時,可以輕松重構(gòu),代碼也將更易讀。
差:
<?phpfunction 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(); }
使用 get 和 set 方法
在 PHP 中,可以為方法設(shè)置 public、protected 和 private 關(guān)鍵字,可以控制對象上的屬性可見性。這是面向?qū)ο蟮脑O(shè)計原則中的開放/封閉原則的一部分。
差:
class BankAccount { public $balance = 1000; } $bankAccount = new BankAccount(); // Buy shoes... $bankAccount->balance -= 100;
好:
class BankAccount { private $balance; public function __construct($balance = 1000) { $this->balance = $balance; } public function withdrawBalance($amount) { if ($amount > $this->balance) { throw new Exception('Amount greater than available balance.'); } $this->balance -= $amount; } public function depositBalance($amount) { $this->balance += $amount; } public function getBalance() { return $this->balance; } } $bankAccount = new BankAccount(); // Buy shoes... $bankAccount->withdrawBalance($shoesPrice); // Get balance $balance = $bankAccount->getBalance();
推薦教程:《PHP教程》