掌握 PHP 中的簡潔程式碼:我的程式設計之旅的主要經驗教訓

DDD
發布: 2024-09-26 06:31:42
原創
876 人瀏覽過

Mastering Clean Code in PHP: Key Lessons from My Coding Journey

「掌握PHP 中的乾淨程式碼:我的編碼之旅的重要經驗教訓」重點介紹實用的實踐規則和範例,以幫助PHP 開發人員編寫乾淨、可維護且高效率的代碼。在這裡,我們將把這些基本規則分解為易於理解的部分,每個部分都附有一個範例。

1. 有意義的名字

  • 規則:為變數、函數和類別使用清晰且描述性的名稱。
  • 為什麼:這使您的程式碼更易於理解和維護。

範例:

   // BAD:
   $x = 25;
   function d($a, $b) {
       return $a + $b;
   }

   // GOOD:
   $age = 25;
   function calculateSum($firstNumber, $secondNumber) {
       return $firstNumber + $secondNumber;
   }
登入後複製

描述

  • 避免使用單字母變量,例如 $x 或 $d。相反,請使用描述性名稱,例如 $age 或calculateSum。
  • 清晰的名稱使您的意圖明確,幫助當前和未來的開發人員理解程式碼的用途。

2. 單一責任原則(SRP)

  • 規則:一個函數或類別應該只有一個改變的理由,這意味著它應該只做一件事。
  • 為什麼:這使您的程式碼更加模組化並且更容易重構。

範例:

   // BAD:
   class Order {
       public function calculateTotal() {
           // logic to calculate total
       }

       public function sendInvoiceEmail() {
           // logic to send email
       }
   }

   // GOOD:
   class Order {
       public function calculateTotal() {
           // logic to calculate total
       }
   }

   class InvoiceMailer {
       public function sendInvoiceEmail() {
           // logic to send email
       }
   }
登入後複製

描述

  • BAD 範例中,Order 類別負責計算總數並發送電子郵件。這違反了 SRP,因為它有兩個責任。
  • GOOD範例中,我們透過建立負責電子郵件任務的 InvoiceMailer 類別來分離關注點,使每個類別更易於管理和更新。

3. 保持函數較小

  • 規則:函數應該做一件事並且做好它。將大函數分解為更小的函數。
  • 為什麼:小函數比較容易理解、測試和維護。

範例:

   // BAD:
   function processOrder($order) {
       // Validate order
       if (!$this->validateOrder($order)) {
           return false;
       }

       // Calculate total
       $total = $this->calculateTotal($order);

       // Send invoice
       $this->sendInvoiceEmail($order);

       return true;
   }

   // GOOD:
   function processOrder($order) {
       if (!$this->isOrderValid($order)) {
           return false;
       }

       $this->finalizeOrder($order);
       return true;
   }

   private function isOrderValid($order) {
       return $this->validateOrder($order);
   }

   private function finalizeOrder($order) {
       $total = $this->calculateTotal($order);
       $this->sendInvoiceEmail($order);
   }
登入後複製

描述

  • BAD 範例中,processOrder 函數嘗試執行所有操作:驗證、計算和發送發票。
  • GOOD 範例中,我們將任務分解為更小、更集中的方法(isOrderValid、finalizeOrder),從而提高了可讀性和可重用性。

4. 避免使用幻數和字串

  • 規則:用命名常數取代「神奇」數字和字串。
  • 為什麼:這提高了可讀性並使程式碼更容易修改。

範例:

   // BAD:
   if ($user->age > 18) {
       echo "Eligible";
   }

   // GOOD:
   define('MINIMUM_AGE', 18);

   if ($user->age > MINIMUM_AGE) {
       echo "Eligible";
   }
登入後複製

描述

  • BAD 範例中,數字 18 是一個「神奇數字」。在分析上下文之前,你不知道它代表什麼。
  • GOOD 範例中,使用 MINIMUM_AGE 使意圖變得清晰,並允許您在一個位置更改值而無需搜尋程式碼庫。

5. DRY(不要重複自己)

  • 規則:避免重複程式碼。盡可能重複使用函數或類別。
  • 為什麼:重複的程式碼更難維護並且更容易出現錯誤。

範例:

   // BAD:
   $total = $itemPrice * $quantity;
   $finalPrice = $total - ($total * $discountRate);

   $cartTotal = $cartItemPrice * $cartQuantity;
   $finalCartPrice = $cartTotal - ($cartTotal * $cartDiscountRate);

   // GOOD:
   function calculateFinalPrice($price, $quantity, $discountRate) {
       $total = $price * $quantity;
       return $total - ($total * $discountRate);
   }

   $finalPrice = calculateFinalPrice($itemPrice, $quantity, $discountRate);
   $finalCartPrice = calculateFinalPrice($cartItemPrice, $cartQuantity, $cartDiscountRate);
登入後複製

描述

  • BAD範例中,價格計算邏輯是重複的。
  • GOOD範例中,我們建立了一個可重複使用的函數calculateFinalPrice以避免重複並使程式碼更易於維護。

6. 使用保護子句來減少巢狀

  • 規則:不使用深層嵌套的if語句,而是提前返回以簡化結構。
  • 為什麼:保護子句消除了不必要的嵌套,使程式碼更乾淨、更易於遵循。

範例:

   // BAD:
   function processPayment($amount) {
       if ($amount > 0) {
           if ($this->isPaymentMethodAvailable()) {
               if ($this->isUserLoggedIn()) {
                   // Process payment
               }
           }
       }
   }

   // GOOD:
   function processPayment($amount) {
       if ($amount <= 0) {
           return;
       }
       if (!$this->isPaymentMethodAvailable()) {
           return;
       }
       if (!$this->isUserLoggedIn()) {
           return;
       }

       // Process payment
   }
登入後複製

描述

  • BAD範例中,邏輯巢狀很深,導致閱讀更加困難。
  • GOOD範例中,保護子句用於在不滿足條件時提前返回,從而扁平化結構並使程式碼更清晰。

7. 評論“為什麼”,而不是“什麼”

  • 規則:寫註解來解釋為什麼會發生某些事情,而不是解釋正在發生的事情(這應該從程式碼中清楚地看出)。
  • 為什麼:註解應該提供超越顯而易見的價值,有助於解釋程式碼背後的意圖和推理。

範例:

   // BAD:
   // Increment age by 1
   $age++;

   // GOOD:
   // User's birthday has passed, increase age by 1
   $age++;
登入後複製

描述

  • The BAD comment simply restates what the code does, which is obvious from the code itself.
  • The GOOD comment explains why we are incrementing the age, adding meaningful context.

8. Refactor for Clarity

  • Rule: Continuously refactor to improve code clarity and simplicity.
  • Why: Clean code is achieved through constant refactoring to ensure that it is always readable, efficient, and maintainable.

Example:

   // Before Refactoring:
   function getDiscountedPrice($price, $isHoliday) {
       if ($isHoliday) {
           return $price * 0.9;
       } else {
           return $price;
       }
   }

   // After Refactoring:
   function getDiscountedPrice($price, $isHoliday) {
       return $isHoliday ? $price * 0.9 : $price;
   }
登入後複製

Description:

  • Refactoring transforms long-winded code into more concise, elegant versions without losing clarity. In this example, we simplified an if-else structure using a ternary operator.

These essential rules—derived from the journey of coding cleanly in PHP—make your code more readable, maintainable, and scalable. By applying these principles consistently, you ensure that your code is easy to understand and modify over time, regardless of the complexity of your projects.

以上是掌握 PHP 中的簡潔程式碼:我的程式設計之旅的主要經驗教訓的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!