Lesson 1
Eliminating Duplicated Code: Extract Functions and Refactor Magic Numbers
Introduction and Context Setting

Welcome to our lesson on eliminating duplicated code and enhancing maintainability by extracting functions and refactoring magic numbers. In modern software development, writing clean and maintainable code is crucial, and refactoring is a key practice that helps achieve this. In this lesson, we'll focus on how to identify duplicate code segments and restructure them to improve readability and maintainability.

Throughout this course, we will be using TypeScript, a popular strongly-typed language based on JavaScript, to ensure type safety, and Jest, a powerful testing framework for performing test-driven development (TDD). These tools facilitate writing reliable tests and managing code evolution seamlessly.

This lesson picks up from 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 improve the codebase.

What is a Code Smells and How Do You Eliminate Them?

Before we delve into speccific "smells", it's important to understand the concept of "code smells." Code smells refer to indicators in the code that may suggest deeper problems, such as poorly structured code or potential defects, but aren't bugs themselves. Some common examples include duplicate code, long methods, and magic numbers. These signals often hinder code readability, maintainability, and can lead to more significant issues over time.

Refactoring patterns provide structured techniques to address these code smells, improving the overall quality of the codebase while avoiding behavioral changes. 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 extracting functions and refactoring magic numbers, to enhance the clarity and adaptability of our application code. We can rely on our tests to ensure that we don't break any existing functionality!

Understanding Code Duplication

The "Code Duplication" smell arises when similar or identical code segments are repeated across a codebase, leading to maintenance difficulties and bugs. For instance, let's consider constant values spread throughout a codebase without clear labeling. This mirroring phenomenon often complicates updates or adjustments, requiring changes in multiple places and increasing the risk of errors.

Maintaining a 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 will fit into our TDD workflow, ensuring minimal disturbance to existing functionalities.

Example: Extracting Functions/Methods

Let's explore how to extract a common logic block as a standalone function using our ShoppingCart class. For this example, assume we initially have repetitive logic calculating the total cost for each item, considering possible discounts. We're starting off with a set of passing tests where there is clear duplication in the implementation.

Refactor - Optimize the Implementation

During refactoring, we integrate calculateItemCost into the ShoppingCart class for broader adoption across all functions needing this logic. With the TDD mindset, all functionality remains intact while elevating code quality.

TypeScript
1export class ShoppingCart { 2 private items: CartItem[] = []; 3 4 addItem(name: string, price: number, quantity: number) { 5 this.items.push({ name, price, quantity }); 6 } 7 8 calculateTotal(): number { 9 let total = 0; 10 11 for (const item of this.items) { 12 let itemTotal = item.price * item.quantity; 13 14 if (item.quantity >= 5) { 15 itemTotal = itemTotal * 0.9; // 10% discount 16 } 17 18 total += itemTotal; 19 } 20 21 return total; 22 } 23 24 calculateTotalWithStudentDiscount(): number { 25 let total = 0; 26 27 for (const item of this.items) { 28 let itemTotal = item.price * item.quantity; 29 30 if (item.quantity >= 5) { 31 itemTotal = 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}

The repetitive logic residing within calculateTotal and calculateTotalWithStudentDiscount functions.

Refactor: Extract Method

We'll extract a method called calculateSubtotal which can be used by calculateTotal and calculateTotalWithStudentDiscount and eliminate the duplication!

TypeScript
1export class ShoppingCart { 2 private items: CartItem[] = []; 3 4 addItem(name: string, price: number, quantity: number) { 5 this.items.push({ name, price, quantity }); 6 } 7 8 calculateSubtotal(): number { 9 let total = 0; 10 11 for (const item of this.items) { 12 let itemTotal = item.price * item.quantity; 13 14 if (item.quantity >= 5) { 15 itemTotal = itemTotal * 0.9; // 10% discount 16 } 17 18 total += itemTotal; 19 } 20 21 return total; 22 } 23 24 calculateTotal(): number { 25 return this.calculateSubtotal(); 26 } 27 28 calculateTotalWithStudentDiscount(): number { 29 let subtotal = this.calculateSubtotal(); 30 31 // Apply student discount 32 return subtotal * 0.85; // 15% student discount 33 } 34}
Example: Refactoring Magic Numbers

Now let's look at "Magic Numbers", which are the oddly specfic number that show up in your code. Magic Numbers can cause maintenance headaches for when these values change in the future, especially if they are used in more than one place. Here's an example:

TypeScript
1function calculateItemCost(item: CartItem) { 2 let itemTotal = item.price * item.quantity; 3 4 if (item.quantity >= 5) { 5 itemTotal *= 0.9; 6 } 7 8 return itemTotal; 9}
Refactor: Extract Magic Numbers

The solution to magic number is simple: hoist them to well-defined constants that can be re-used throughout the codebase.

TypeScript
1const BULK_DISCOUNT_THRESHOLD = 5; 2const BULK_DISCOUNT_RATE = 0.9; // 10% discount 3 4function calculateItemCost(item: CartItem) { 5 let itemTotal = item.price * item.quantity; 6 7 if (item.quantity >= BULK_DISCOUNT_THRESHOLD) { 8 itemTotal *= BULK_DISCOUNT_RATE; 9 } 10 11 return itemTotal; 12}
Review, Summary, and Preparation for Practice

In this lesson, we explored the significance 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.

Now, as you prepare for upcoming practice exercises, focus on applying these skills to further enhance your ability to manage complex codebases. Employ the concepts of DRY and TDD consistently to maintain robust, adaptable code. Keep practicing and mastering these principles, and you’ll soon find yourself developing highly efficient and scalable applications.

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