Introduction and Context Setting

Welcome to our lesson on eliminating duplicated code and enhancing maintainability through method extraction and refactoring magic numbers. Writing clean and maintainable code is crucial in modern software development, and refactoring is a key practice that helps achieve these goals. This lesson focuses on identifying duplicate code segments and restructuring them to improve readability and maintainability.

Throughout this course, we will be using Kotlin, a modern, concise, and expressive programming language that runs on the JVM, designed to work seamlessly with existing Java code. We'll leverage JUnit, a widely used testing framework, for test-driven development (TDD).

This lesson builds upon an existing ShoppingCart example to focus on the Refactor step of the Red-Green-Refactor cycle. Let's dive into identifying and refactoring duplicated code to enhance the quality of our codebase.

What are Code Smells and How Do You Eliminate Them?

Before we delve into specific "smells," it's important to understand what "code smells" are. Code smells are indicators in the code suggesting deeper problems, such as poorly structured code or potential defects, though they aren't bugs themselves. Common examples include duplicate code, long methods, and magic numbers. These signals can hinder code readability and maintainability and may eventually lead to significant issues.

Refactoring patterns provide structured techniques to address these code smells, improving the overall quality of the codebase while maintaining its behavior. By employing these patterns, we can systematically transform problematic sections into cleaner, more efficient code. In this lesson, we'll target duplications by leveraging refactoring patterns, such as method extraction and refactoring magic numbers, to enhance the clarity and adaptability of our code. We can rely on our tests to ensure that we don't break any existing functionality!

Understanding Code Duplication

"Code Duplication" is a code smell that occurs when similar or identical code segments are repeated across a codebase, leading to maintenance difficulties and bugs. Consider constant values spread throughout a codebase without clear labeling. This mirroring phenomenon complicates updates or adjustments, requiring changes in multiple places, and increases the risk of errors.

Adhering to the DRY (Don't Repeat Yourself) principle ensures each piece of knowledge has a single, unambiguous representation within the system. This leads to better maintainability and understandability, reducing troubleshooting and debugging efforts. Remember, refactoring to eliminate code duplication fits into our TDD workflow, ensuring minimal disturbance to existing functionalities.

Example: Extracting Methods

Let's explore how to extract a common logic block as a standalone method using our ShoppingCart class. Initially, we have repetitive logic calculating the total cost for each item, considering possible discounts. We start with a set of passing tests where there is clear duplication in the implementation.

Refactor - Optimize the Implementation

During refactoring, we integrate calculateSubtotal into the ShoppingCart class for broader adoption across all methods needing this logic. With the TDD mindset, all functionality remains intact while elevating code quality. We can view the initial implementation next:

Kotlin
1class ShoppingCart { 2 private val items = mutableListOf<CartItem>() 3 4 fun addItem(name: String, price: Double, quantity: Int) { 5 items.add(CartItem(name, price, quantity)) 6 } 7 8 fun calculateTotal(): Double { 9 var total = 0.0 10 11 for (item in items) { 12 var itemTotal = item.price * item.quantity 13 14 if (item.quantity >= 5) { 15 itemTotal *= 0.9 // 10% discount 16 } 17 18 total += itemTotal 19 } 20 21 return total 22 } 23 24 fun calculateTotalWithStudentDiscount(): Double { 25 var total = 0.0 26 27 for (item in items) { 28 var itemTotal = item.price * item.quantity 29 30 if (item.quantity >= 5) { 31 itemTotal *= 0.9 // 10% discount 32 } 33 34 total += itemTotal 35 } 36 37 // Apply student discount 38 return total * 0.85 // 15% student discount 39 } 40} 41 42data class CartItem(val name: String, val price: Double, val quantity: Int)

The repetitive logic resides within the calculateTotal and calculateTotalWithStudentDiscount methods.

Refactor: Extract Method

We'll extract a method called calculateSubtotal, which can be used by calculateTotal and calculateTotalWithStudentDiscount to eliminate duplication.

Kotlin
1class ShoppingCart { 2 private val items = mutableListOf<CartItem>() 3 4 fun addItem(name: String, price: Double, quantity: Int) { 5 items.add(CartItem(name, price, quantity)) 6 } 7 8 private fun calculateSubtotal(): Double { 9 var total = 0.0 10 11 for (item in items) { 12 var itemTotal = item.price * item.quantity 13 14 if (item.quantity >= 5) { 15 itemTotal *= 0.9 // 10% discount 16 } 17 18 total += itemTotal 19 } 20 21 return total 22 } 23 24 fun calculateTotal(): Double { 25 return calculateSubtotal() 26 } 27 28 fun calculateTotalWithStudentDiscount(): Double { 29 val subtotal = calculateSubtotal() 30 31 // Apply student discount 32 return subtotal * 0.85 // 15% student discount 33 } 34}
Example: Refactoring Magic Numbers

Next, we'll address "Magic Numbers," which are the oddly specific numbers that appear in your code. Magic numbers can cause maintenance headaches when these values need to change, especially if used in multiple places. Here's an example:

Kotlin
1fun calculateItemCost(item: CartItem): Double { 2 var itemTotal = item.price * item.quantity 3 4 if (item.quantity >= 5) { 5 itemTotal *= 0.9 6 } 7 8 return itemTotal 9}

There are two "magic numbers" in this code that make it less maintainable:

  • 5
  • 0.9
Refactor: Extract Magic Numbers

The solution to magic numbers is simple: elevate them to well-defined constants that can be broadly used across the codebase.

Kotlin
1class ShoppingCart { 2 companion object { 3 private const val BULK_DISCOUNT_THRESHOLD = 5 4 private const val BULK_DISCOUNT_RATE = 0.9 // 10% discount 5 } 6 7 fun calculateItemCost(item: CartItem): Double { 8 var itemTotal = item.price * item.quantity 9 10 if (item.quantity >= BULK_DISCOUNT_THRESHOLD) { 11 itemTotal *= BULK_DISCOUNT_RATE 12 } 13 14 return itemTotal 15 } 16}
Review, Summary, and Preparation for Practice

In this lesson, we explored the importance of refactoring to eliminate code duplication and magic numbers. By adhering to the TDD cycle — Red (write a failing test), Green (implement with minimal code), and Refactor (improve quality while ensuring behavior remains unchanged) — we ensure our code remains both functional and maintainable.

As you prepare for upcoming practice exercises, focus on applying these skills to strengthen your ability to manage complex codebases. Consistently apply the principles of DRY and TDD to maintain robust, adaptable code. Keep practicing and mastering these principles, and you’ll soon find yourself developing highly efficient and scalable applications in Kotlin.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal