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!
Code smells
are signs that something could be amiss in our code. You could compare them to an unpleasant smell in a room. But instead of indicating rotten food or a dirty sock, they signal that our code may not be as readable, efficient, or manageable as it could be.
Consider this bit of code:
Java1public class PriceCalculator { 2 public static int calculate(int quantity, int price) { 3 return quantity * price; 4 } 5 6 public static void main(String[] args) { 7 int total = calculate(5, 3); 8 System.out.println(total); 9 } 10}
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.
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:
Java1int totalApplesPrice = quantityApples * priceApple - 5; 2int 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:
Java1public class PriceCalculator { 2 public static int calculatePrice(int quantity, int price) { 3 int discount = 5; 4 return quantity * price - discount; 5 } 6 7 public static void main(String[] args) { 8 int totalApplesPrice = calculatePrice(quantityApples, priceApple); 9 int totalBananasPrice = calculatePrice(quantityBananas, priceBanana); 10 System.out.println(totalApplesPrice); 11 System.out.println(totalBananasPrice); 12 } 13}
With this solution, if we need to change the discount
or the formula, we can do so in one place: the calculatePrice
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:
Java1public class OrderProcessor { 2 public boolean processOrder(Order order) { 3 System.out.println("Processing order..."); 4 if (order.isValid()) { 5 System.out.println("Order is valid"); 6 if (order.paymentType.equals("credit_card")) { 7 processCreditCardPayment(order); 8 sendOrderConfirmationEmail(order); 9 } else if (order.paymentType.equals("paypal")) { 10 processPaypalPayment(order); 11 sendOrderConfirmationEmail(order); 12 } else if (order.paymentType.equals("bank_transfer")) { 13 processBankTransferPayment(order); 14 sendOrderConfirmationEmail(order); 15 } else { 16 System.out.println("Unsupported payment type"); 17 return false; 18 } 19 System.out.println("Order processed successfully!"); 20 return true; 21 } else { 22 System.out.println("Invalid order"); 23 return false; 24 } 25 } 26}
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:
Java1public class OrderProcessor { 2 public boolean processPayment(String paymentType, Order order) { 3 if (paymentType.equals("credit_card")) { 4 processCreditCardPayment(order); 5 } else if (paymentType.equals("paypal")) { 6 processPaypalPayment(order); 7 } else if (paymentType.equals("bank_transfer")) { 8 processBankTransferPayment(order); 9 } else { 10 System.out.println("Unsupported payment type"); 11 return false; 12 } 13 return true; 14 } 15 16 public boolean processOrder(Order order) { 17 System.out.println("Processing order..."); 18 if (!order.isValid()) { 19 System.out.println("Invalid order"); 20 return false; 21 } 22 if (processPayment(order.paymentType, order)) { 23 sendOrderConfirmationEmail(order); 24 System.out.println("Order processed successfully!"); 25 return true; 26 } else { 27 return false; 28 } 29 } 30}
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:
Java1public class Triangle { 2 public static double calculateTriangleArea(double base, double height) { 3 // Calculate the area of a triangle 4 // Formula: 0.5 * base * height 5 double area = 0.5 * base * height; // Area calculation 6 return area; // Return the result 7 } 8}
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.
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:
Java1public int func(int a, int b) { 2 return a * 10 + b; 3}
The names func
, a
, and b
don't tell us much about what is happening. A better version could be this:
Java1public int calculateScore(int baseScore, int extraPoints) { 2 return baseScore * 10 + extraPoints; 3}
In this version, each name describes the data or action it represents, making the code easier to read.
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, improve your code's efficiency, readability, and maintainability. How exciting is that? Let's move ahead!