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 C#, a modern object-oriented programming language, to ensure robust, type-safe applications. We'll leverage xUnit, a popular testing framework, for test-driven development (TDD), and Moq, a versatile mocking library, to facilitate writing reliable tests and managing code evolution effortlessly.
This lesson picks up from an existing ShoppingCart
example to concentrate on the Refactor step of the Red-Green-Refactor cycle. Let's dive into identifying and refactoring duplicated code to enhance the codebase's quality.
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!
"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 increasing 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.
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.
During refactoring, we integrate CalculateItemCost
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.
C#1public class ShoppingCart 2{ 3 private List<CartItem> items = new List<CartItem>(); 4 5 public void AddItem(string name, decimal price, int quantity) 6 { 7 items.Add(new CartItem { Name = name, Price = price, Quantity = quantity }); 8 } 9 10 public decimal CalculateTotal() 11 { 12 decimal total = 0; 13 14 foreach (var item in items) 15 { 16 decimal itemTotal = item.Price * item.Quantity; 17 18 if (item.Quantity >= 5) 19 { 20 itemTotal *= 0.9m; // 10% discount 21 } 22 23 total += itemTotal; 24 } 25 26 return total; 27 } 28 29 public decimal CalculateTotalWithStudentDiscount() 30 { 31 decimal total = 0; 32 33 foreach (var item in items) 34 { 35 decimal itemTotal = item.Price * item.Quantity; 36 37 if (item.Quantity >= 5) 38 { 39 itemTotal *= 0.9m; // 10% discount 40 } 41 42 total += itemTotal; 43 } 44 45 // Apply student discount 46 return total * 0.85m; // 15% student discount 47 } 48}
The repetitive logic resides within the CalculateTotal
and CalculateTotalWithStudentDiscount
methods.
We'll extract a method called CalculateSubtotal
, which can be used by CalculateTotal
and CalculateTotalWithStudentDiscount
to eliminate duplication.
C#1public class ShoppingCart 2{ 3 private List<CartItem> items = new List<CartItem>(); 4 5 public void AddItem(string name, decimal price, int quantity) 6 { 7 items.Add(new CartItem { Name = name, Price = price, Quantity = quantity }); 8 } 9 10 private decimal CalculateSubtotal() 11 { 12 decimal total = 0; 13 14 foreach (var item in items) 15 { 16 decimal itemTotal = item.Price * item.Quantity; 17 18 if (item.Quantity >= 5) 19 { 20 itemTotal *= 0.9m; // 10% discount 21 } 22 23 total += itemTotal; 24 } 25 26 return total; 27 } 28 29 public decimal CalculateTotal() 30 { 31 return CalculateSubtotal(); 32 } 33 34 public decimal CalculateTotalWithStudentDiscount() 35 { 36 decimal subtotal = CalculateSubtotal(); 37 38 // Apply student discount 39 return subtotal * 0.85m; // 15% student discount 40 } 41}
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:
C#1public static decimal CalculateItemCost(CartItem item) 2{ 3 decimal itemTotal = item.Price * item.Quantity; 4 5 if (item.Quantity >= 5) 6 { 7 itemTotal *= 0.9m; 8 } 9 10 return itemTotal; 11}
There are two "Magic Numbers" in this code that make it less maintainable:
- 5
- 0.9m
The solution to magic numbers is simple: elevate them to well-defined constants that can be broadly used across the codebase.
C#1private const int BULK_DISCOUNT_THRESHOLD = 5; 2private const decimal BULK_DISCOUNT_RATE = 0.9m; // 10% discount 3 4public static decimal CalculateItemCost(CartItem item) 5{ 6 decimal itemTotal = item.Price * item.Quantity; 7 8 if (item.Quantity >= BULK_DISCOUNT_THRESHOLD) 9 { 10 itemTotal *= BULK_DISCOUNT_RATE; 11 } 12 13 return itemTotal; 14}
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 C#.