標籤:

編寫整潔的 PHP 代碼

簡評: Clean Code PHP,是基於羅伯特·馬丁的經典編程書籍 ——「代碼整潔之道」的 PHP 適用版本,並不是一個風格指南,而是在 PHP 中編寫可讀、可重用和可重構的軟體的指南。當然切忌機械地遵循這裡的原則。

不添加不需要的上下文

如果你的類名或對象名稱有具體的含義,請不要重複該變數的名稱。

差:

<?phpclass Car{ public $carMake; public $carModel; public $carColor; //...}

好:

<?phpclass Car{ public $make; public $model; public $color; //...}

函數參數數量(理想情況是 2 個以下)

限制函數參數的數量是非常重要的,因為它讓函數更容易測試,參數超過三個的話,你必須用每個單獨的參數測試大量不同的情況。

無參數是理想的情況。一個或兩個參數是可以的,但應該避免三個。通常,如果你有兩個以上的參數,那麼你的函數試圖完成太多的功能,若不是,大多數時候,較高級的對象就足以作為參數(譯者註:比如數組、對象)。

差:

<?phpfunction 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) { // ...}

一個函數應該只完成一件事

這是軟體工程中最重要的規則。當函數做的事多於一件事情時,他們更難編寫和測試。 當你可以將函數隔離成一個動作時,可以輕鬆重構,代碼也將更易讀。

差:

<?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 中,可以為方法設置 public、protected 和 private 關鍵字,可以控制對象上的屬性可見性。這是面向對象的設計原則中的開放/封閉原則的一部分。

差:

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();

原文:Clean Code Concepts Adapted for PHP

擴展閱讀:

  • 2017 年你應該學習一下下函數式編程
  • Python 家族有多龐大
  • jupeter/clean-code-php

歡迎關注

  • 知乎專欄「極光日報」,每天為 Makers 導讀三篇優質英文文章。
  • 網易雲電台「極光日報」,上下班路上為你讀報。
  • 微信公眾號「極光開發者」,每周兩篇技術類乾貨。

推薦閱讀:

404為什麼是404而不是其他的數字?
據說雷軍今天下午指導了程序猿寫代碼,現在的雷軍真能指導嗎?

TAG:PHP | 代码 |