Welcome to the very first lesson of the "Applying Clean Code Principles" course! In this lesson, we will focus on a fundamental concept in clean coding: the DRY ("Don't Repeat Yourself") principle. Understanding DRY is crucial for writing efficient, maintainable, and clean code. This principle is not just important for coding interviews but also in everyday software development. Today, we will dive deep into issues caused by repetitive code and explore strategies to combat redundancy. 🚀
Repetitive functionality in code can introduce several issues that affect the efficiency and maintainability of your software:
-
Code Bloat: Repeating similar code across different parts of your application unnecessarily increases the size of the codebase. This makes the code harder to navigate and increases the chances of introducing errors.
-
Risk of Inconsistencies: When similar pieces of logic are scattered across different areas, it's easy for them to become out of sync during updates or bug fixes. This can result in logic discrepancies and potentially introduce new problems.
-
Maintenance Challenges: Updating code often requires modifications in multiple places, leading to increased work and a higher likelihood of errors. Redundant code makes it difficult for developers to ensure all necessary changes have been made consistently.
To adhere to the DRY principle and avoid repeating yourself, several strategies can be employed:
-
Extracting Function: Move repeated logic into a dedicated function that can be called wherever needed. This promotes reuse and simplifies updates.
-
Extracting Variable: Consolidate repeated expressions or values into variables. This centralizes change, reducing the potential for errors.
-
Replace Temp with Query: Use a function to compute values on demand rather than storing them in temporary variables, aiding in readability and reducing redundancy.
Consider the following problematic code snippet written in Go, where repetitive logic is used for calculating the total price based on different shipping methods:
Go1func calculateClickAndCollectTotal(order Order) float64 { 2 itemsTotal := 0.0 3 for _, item := range order.Items { 4 itemsTotal += item.Price * float64(item.Quantity) 5 } 6 shippingCost := 0.0 7 if itemsTotal <= 100 { 8 shippingCost = 5 9 } 10 return itemsTotal + shippingCost + order.Tax 11} 12 13func calculatePostShipmentTotal(order Order, isExpress bool) float64 { 14 itemsTotal := 0.0 15 for _, item := range order.Items { 16 itemsTotal += item.Price * float64(item.Quantity) 17 } 18 shippingCost := 0.0 19 if isExpress { 20 shippingCost = itemsTotal * 0.1 21 } else { 22 shippingCost = itemsTotal * 0.05 23 } 24 return itemsTotal + shippingCost + order.Tax 25}
Both functions contain duplicated logic for calculating the total price of items, making them error-prone and hard to maintain. Now, let's refactor this code.
By consolidating the shared logic into a separate function, we can eliminate redundancy and streamline updates:
Go1func calculateClickAndCollectTotal(order Order) float64 { 2 itemsTotal := calculateItemsTotal(order) 3 shippingCost := 0.0 4 if itemsTotal <= 100 { 5 shippingCost = 5 6 } 7 return itemsTotal + shippingCost + order.Tax 8} 9 10func calculatePostShipmentTotal(order Order, isExpress bool) float64 { 11 itemsTotal := calculateItemsTotal(order) 12 shippingCost := 0.0 13 if isExpress { 14 shippingCost = itemsTotal * 0.1 15 } else { 16 shippingCost = itemsTotal * 0.05 17 } 18 return itemsTotal + shippingCost + order.Tax 19} 20 21func calculateItemsTotal(order Order) float64 { 22 itemsTotal := 0.0 23 for _, item := range order.Items { 24 itemsTotal += item.Price * float64(item.Quantity) 25 } 26 return itemsTotal 27}
By extracting the calculateItemsTotal
function, we centralize the logic of item total calculation, leading to cleaner, more maintainable code.
Let's look at another example dealing with repeated calculations for discount rates in Go:
Go1func applyDiscount(price float64, customer Customer) float64 { 2 loyaltyDiscount := customer.LoyaltyLevel * 0.02 3 price *= (1 - loyaltyDiscount) 4 // Additional discounts 5 seasonalDiscount := 0.10 6 price *= (1 - seasonalDiscount) 7 return price 8}
Here, the discount rates are scattered throughout the code, which complicates management and updates.
We can simplify this by extracting the discount rates into variables:
Go1func applyDiscount(price float64, customer Customer) float64 { 2 loyaltyDiscount := customer.LoyaltyLevel * 0.02 3 seasonalDiscount := 0.10 4 5 totalDiscount := 1 - (loyaltyDiscount + seasonalDiscount) 6 price *= totalDiscount 7 8 return price 9}
Now, with the totalDiscount
variable, the logic is cleaner and more readable, allowing changes in just one place. 🎉
Our final example involves temporary variables that lead to repetition:
Go1func isEligibleForDiscount(customer Customer) bool { 2 newCustomer := customer.SignUpDate.After(time.Now().AddDate(0, -3, 0)) 3 return newCustomer && len(customer.PurchaseHistory) > 5 4} 5 6func isEligibleForLoyaltyProgram(customer Customer) bool { 7 newCustomer := customer.SignUpDate.After(time.Now().AddDate(0, -3, 0)) 8 return newCustomer || customer.LoyaltyLevel > 3 9}
The variable newCustomer
is used in multiple places, causing duplicated logic.
Let's refactor by extracting the logic into a function, reducing duplication and enhancing modularity:
Go1func isEligibleForDiscount(customer Customer) bool { 2 return isNewCustomer(customer) && len(customer.PurchaseHistory) > 5 3} 4 5func isEligibleForLoyaltyProgram(customer Customer) bool { 6 return isNewCustomer(customer) || customer.LoyaltyLevel > 3 7} 8 9func isNewCustomer(customer Customer) bool { 10 return customer.SignUpDate.After(time.Now().AddDate(0, -3, 0)) 11}
By creating the isNewCustomer
function, we've simplified the code and made it more maintainable. 🚀
In this lesson, you learned about the DRY principle and strategies like Extracting Function, Extracting Variable, and Replace Temp with Query to eliminate code redundancy. These strategies help to create code that is easier to maintain, enhance, and understand. Next, you'll have the opportunity to apply these concepts in practical exercises, strengthening your ability to refactor code and uphold clean coding standards. Happy coding! 😊