Lesson 1
Refactoring with Kotlin: Identifying and Eliminating Code Smells
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 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:

Kotlin
1class PriceCalculator { 2 companion object { 3 fun calculate(quantity: Int, price: Int): Int { 4 return quantity * price 5 } 6 7 @JvmStatic 8 fun main(args: Array<String>) { 9 val total = calculate(5, 3) 10 println(total) 11 } 12 } 13}

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.

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:

Kotlin
1val totalApplesPrice = quantityApples * priceApple - 5 2val 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:

Kotlin
1class PriceCalculator { 2 companion object { 3 fun calculatePrice(quantity: Int, price: Int): Int { 4 val discount = 5 5 return quantity * price - discount 6 } 7 8 @JvmStatic 9 fun main(args: Array<String>) { 10 val quantityApples = 10 11 val priceApple = 2 12 val quantityBananas = 8 13 val priceBanana = 3 14 15 val totalApplesPrice = calculatePrice(quantityApples, priceApple) 16 val totalBananasPrice = calculatePrice(quantityBananas, priceBanana) 17 println(totalApplesPrice) 18 println(totalBananasPrice) 19 } 20 } 21}

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:

Kotlin
1class OrderProcessor { 2 fun processOrder(order: Order): Boolean { 3 println("Processing order...") 4 if (order.isValid()) { 5 println("Order is valid") 6 if (order.paymentType == "credit_card") { 7 processCreditCardPayment(order) 8 sendOrderConfirmationEmail(order) 9 } else if (order.paymentType == "paypal") { 10 processPaypalPayment(order) 11 sendOrderConfirmationEmail(order) 12 } else if (order.paymentType == "bank_transfer") { 13 processBankTransferPayment(order) 14 sendOrderConfirmationEmail(order) 15 } else { 16 println("Unsupported payment type") 17 return false 18 } 19 println("Order processed successfully!") 20 return true 21 } else { 22 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:

Kotlin
1class OrderProcessor { 2 fun processPayment(paymentType: String, order: Order): Boolean { 3 return when (paymentType) { 4 "credit_card" -> { 5 processCreditCardPayment(order) 6 true 7 } 8 "paypal" -> { 9 processPaypalPayment(order) 10 true 11 } 12 "bank_transfer" -> { 13 processBankTransferPayment(order) 14 true 15 } 16 else -> { 17 println("Unsupported payment type") 18 false 19 } 20 } 21 } 22 23 fun processOrder(order: Order): Boolean { 24 println("Processing order...") 25 if (!order.isValid()) { 26 println("Invalid order") 27 return false 28 } 29 if (processPayment(order.paymentType, order)) { 30 sendOrderConfirmationEmail(order) 31 println("Order processed successfully!") 32 return true 33 } else { 34 return false 35 } 36 } 37}
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 method, which calculates the area of a triangle, with comments:

Kotlin
1class Triangle { 2 fun calculateTriangleArea(base: Double, height: Double): Double { 3 // Calculate the area of a triangle 4 // Formula: 0.5 * base * height 5 val 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.

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:

Kotlin
1fun func(a: Int, b: Int): Int { 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:

Kotlin
1fun calculateScore(baseScore: Int, extraPoints: Int): Int { 2 return baseScore * 10 + extraPoints 3}

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.