Lesson 1
Applying the DRY Principle in C++
Introduction

Welcome to the very first lesson of the "Applying Clean Code Principles in C++" 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. 🚀

Understanding the Problem

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.

DRY Strategies

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 whenever 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.

Extracting Function

Consider the following problematic code snippet where repetitive logic is used for calculating the total price based on different shipping methods:

C++
1double calculateClickAndCollectTotal(Order order) { 2 double itemsTotal = 0; 3 for (Item item : order.getItems()) { 4 itemsTotal += item.getPrice() * item.getQuantity(); 5 } 6 double shippingCost = itemsTotal > 100 ? 0 : 5; 7 return itemsTotal + shippingCost + order.getTax(); 8} 9 10double calculatePostShipmentTotal(Order order, bool isExpress) { 11 double itemsTotal = 0; 12 for (Item item : order.getItems()) { 13 itemsTotal += item.getPrice() * item.getQuantity(); 14 } 15 double shippingCost = isExpress ? itemsTotal * 0.1 : itemsTotal * 0.05; 16 return itemsTotal + shippingCost + order.getTax(); 17}

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.

Extracting Function: Refactored

By consolidating the shared logic into a separate function, we can eliminate redundancy and streamline updates:

C++
1double calculateClickAndCollectTotal(Order order) { 2 double itemsTotal = calculateItemsTotal(order); 3 double shippingCost = itemsTotal > 100 ? 0 : 5; 4 return itemsTotal + shippingCost + order.getTax(); 5} 6 7double calculatePostShipmentTotal(Order order, bool isExpress) { 8 double itemsTotal = calculateItemsTotal(order); 9 double shippingCost = isExpress ? itemsTotal * 0.1 : itemsTotal * 0.05; 10 return itemsTotal + shippingCost + order.getTax(); 11} 12 13double calculateItemsTotal(Order order) { 14 double itemsTotal = 0; 15 for (Item item : order.getItems()) { 16 itemsTotal += item.getPrice() * item.getQuantity(); 17 } 18 return itemsTotal; 19}

By extracting the calculateItemsTotal function, we centralize the logic of item total calculation, leading to cleaner, more maintainable code.

Extracting Variable

Let's look at another example dealing with repeated calculations for discount rates:

C++
1double applyDiscount(double price, Customer customer) { 2 double loyaltyDiscount = customer.getLoyaltyLevel() * 0.02; 3 price *= (1 - loyaltyDiscount); 4 // Additional discounts 5 double 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.

Extracting Variable: Refactored

We can simplify this by extracting the discount rates into variables:

C++
1double applyDiscount(double price, Customer customer) { 2 double loyaltyDiscount = customer.getLoyaltyLevel() * 0.02; 3 double seasonalDiscount = 0.10; 4 5 double totalDiscount = 1 - loyaltyDiscount - seasonalDiscount; 6 price *= totalDiscount; 7 8 return price; 9}

Now, with the totalDiscount variable, the logic is cleaner, more readable, and allows changes in just one place. 🎉

Replace Temp with Query

Our final example involves temporary variables that lead to repetition:

C++
1bool isEligibleForDiscount(Customer customer) { 2 bool newCustomer = customer.getSignupDate() > (getCurrentDate() - 90); 3 return newCustomer && customer.getPurchaseHistory().size() > 5; 4} 5 6bool isEligibleForLoyaltyProgram(Customer customer) { 7 bool newCustomer = customer.getSignupDate() > (getCurrentDate() - 90); 8 return newCustomer || customer.getLoyaltyLevel() > 3; 9}

The variable newCustomer is used in multiple places, causing duplicated logic.

Replace Temp with Query: Refactored

Let's refactor by extracting the logic into a function, reducing duplication and enhancing modularity:

C++
1bool isEligibleForDiscount(Customer customer) { 2 return isNewCustomer(customer) && customer.getPurchaseHistory().size() > 5; 3} 4 5bool isEligibleForLoyaltyProgram(Customer customer) { 6 return isNewCustomer(customer) || customer.getLoyaltyLevel() > 3; 7} 8 9bool isNewCustomer(Customer customer) { 10 return customer.getSignupDate() > (getCurrentDate() - 90); 11}

By creating the isNewCustomer function, we've simplified the code and made it more maintainable. 🚀

Summary and Preparation for Practice

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! 😊

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