首页  >  文章  >  后端开发  >  掌握 PHP 中的简洁代码:我的编码之旅的主要经验教训

掌握 PHP 中的简洁代码:我的编码之旅的主要经验教训

DDD
DDD原创
2024-09-26 06:31:42855浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn