「掌握PHP 中的乾淨程式碼:我的編碼之旅的重要經驗教訓」重點介紹實用的實踐規則和範例,以幫助PHP 開發人員編寫乾淨、可維護且高效率的代碼。在這裡,我們將把這些基本規則分解為易於理解的部分,每個部分都附有一個範例。
範例:
// BAD: $x = 25; function d($a, $b) { return $a + $b; } // GOOD: $age = 25; function calculateSum($firstNumber, $secondNumber) { return $firstNumber + $secondNumber; }
描述:
範例:
// 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: 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: if ($user->age > 18) { echo "Eligible"; } // GOOD: define('MINIMUM_AGE', 18); if ($user->age > MINIMUM_AGE) { echo "Eligible"; }
描述:
範例:
// 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: 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: // Increment age by 1 $age++; // GOOD: // User's birthday has passed, increase age by 1 $age++;
描述:
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:
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中文網其他相關文章!