Lesson 1
Refactoring with Code Smells in PHP
Topic Overview

Welcome to the world of refactoring! In this lesson, we're learning about Code Smells, which are patterns in code that hint at potential problems. Our mission is to help you spot these smells and understand how to improve them or, in programming terms, how to refactor them. We'll delve into the concept of code smells, examine different types, and apply real-world code examples to solidify your understanding. Let's get started!

Introduction to Code Smells

Code smells are signs that something could be amiss in your code. You could compare them to an unpleasant smell in a room. Instead of indicating rotten food or a dirty sock, they signal that your code may not be as readable, efficient, or manageable as it could be.

Consider this bit of code:

php
1<?php 2class PriceCalculator 3{ 4 public static function calculate($quantity, $price) 5 { 6 return $quantity * $price; 7 } 8} 9 10$total = PriceCalculator::calculate(5, 3); 11echo $total;

The function name calculate is too vague. What exactly does it calculate? For whom? This ambiguity is a sign of a bad naming code smell. Let's see how this and other code smells can be improved!

Duplicate Code

If you notice the same piece of code in more than one place, you may be looking at an example of the Duplicate Code smell. Duplicate code leaves room for errors and bugs. If you need to make a change, you might overlook one instance of duplication.

Here's an example:

php
1$totalApplesPrice = $quantityApples * $priceApple - 5; 2$totalBananasPrice = $quantityBananas * $priceBanana - 5;

This code performs the same operation on different data. Instead of duplicating the operation, we can create a method to handle it:

php
1<?php 2class PriceCalculator 3{ 4 public static function calculatePrice($quantity, $price) 5 { 6 $discount = 5; 7 return $quantity * $price - $discount; 8 } 9 10 public static function main() 11 { 12 $totalApplesPrice = self::calculatePrice($quantityApples, $priceApple); 13 $totalBananasPrice = self::calculatePrice($quantityBananas, $priceBanana); 14 echo $totalApplesPrice; 15 echo $totalBananasPrice; 16 } 17}

With this solution, if we need to change the discount or the formula, we can do so in one place: the calculatePrice method.

Too Long Method

A method that does too many things or is too long is harder to read and understand, making it a prime candidate for the Too Long Method smell.

Consider this example:

php
1<?php 2class OrderProcessor 3{ 4 public function processOrder($order) 5 { 6 echo "Processing order..."; 7 if ($order->isValid()) { 8 echo "Order is valid"; 9 if ($order->paymentType == "credit_card") { 10 $this->processCreditCardPayment($order); 11 $this->sendOrderConfirmationEmail($order); 12 } elseif ($order->paymentType == "paypal") { 13 $this->processPaypalPayment($order); 14 $this->sendOrderConfirmationEmail($order); 15 } elseif ($order->paymentType == "bank_transfer") { 16 $this->processBankTransferPayment($order); 17 $this->sendOrderConfirmationEmail($order); 18 } else { 19 echo "Unsupported payment type"; 20 return false; 21 } 22 echo "Order processed successfully!"; 23 return true; 24 } else { 25 echo "Invalid order"; 26 return false; 27 } 28 } 29}

This function handles too many aspects of order processing, suggesting a Too Long Method smell. A better approach could involve breaking down the functionality into smaller, more focused methods.

For example, the updated code can look like this:

php
1<?php 2class OrderProcessor 3{ 4 public function processPayment($paymentType, $order) 5 { 6 if ($paymentType == "credit_card") { 7 $this->processCreditCardPayment($order); 8 } elseif ($paymentType == "paypal") { 9 $this->processPaypalPayment($order); 10 } elseif ($paymentType == "bank_transfer") { 11 $this->processBankTransferPayment($order); 12 } else { 13 echo "Unsupported payment type"; 14 return false; 15 } 16 return true; 17 } 18 19 public function processOrder($order) 20 { 21 echo "Processing order..."; 22 if (!$order->isValid()) { 23 echo "Invalid order"; 24 return false; 25 } 26 if ($this->processPayment($order->paymentType, $order)) { 27 $this->sendOrderConfirmationEmail($order); 28 echo "Order processed successfully!"; 29 return true; 30 } else { 31 return false; 32 } 33 } 34}
Comment Abuse

Comments within your code should provide useful information, but remember, too much of a good thing can be a problem. Over-commenting can distract from the code itself and, more often than not, it's a sign the code isn't clear enough.

Consider this revised method, which calculates the area of a triangle, now with comments:

php
1<?php 2class Triangle 3{ 4 public static function calculateTriangleArea($baseValue, $height) 5 { 6 // Calculate the area of a triangle 7 // Formula: 0.5 * base * height 8 $area = 0.5 * $baseValue * $height; // Area calculation 9 return $area; // Return the result 10 } 11}

While comments explaining the formula might be helpful for some, the code itself is quite straightforward, and the comments on the calculation itself might be seen as unnecessary. If the method's name and parameters are clear, the need for additional comments can be minimized.

Here is how we could change this:

php
1<?php 2class Triangle 3{ 4 // Calculates the area of a triangle using the given base and height. 5 public static function calculateTriangleArea($baseValue, $height) 6 { 7 $area = 0.5 * $baseValue * $height; 8 return $area; 9 } 10}

In this version, a single comment placed at the method level provides a high-level overview of what the method does, which is sufficient given the clarity of the method name and parameters. Comments within the method have been removed as they were unnecessary.

Bad Naming

Finally, we have Bad Naming. As the name suggests, this smell occurs when names don't adequately explain what a variable, method, or class does. Good names are crucial for readable, understandable code.

Take a look at the following example:

php
1public function func($a, $b) 2{ 3 return $a * 10 + $b; 4}

The names func, $a, and $b don't tell us much about what is happening. A better version could be this:

php
1public function calculateScore($baseScore, $extraPoints) 2{ 3 return $baseScore * 10 + $extraPoints; 4}

In this version, each name describes the data or action it represents, making the code easier to read.

Lesson Summary

We've discovered Code Smells and studied common types: Duplicate Code, Too Long Method, Comment Abuse, and Bad Naming. Now you can spot code smells and understand how they can signal a problem in your code.

In the upcoming real-world example-based practice sessions, you'll enhance your debugging skills and improve your code's efficiency, readability, and maintainability. How exciting is that? Let's move ahead!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.