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 that all necessary changes have been made consistently.
To adhere to the DRY principle and avoid repeating yourself, several strategies can be employed:
-
Extracting Method: Move repeated logic into a dedicated method 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 method to compute values on demand rather than storing them in temporary variables, aiding in readability and reducing redundancy.
Consider the following problematic code snippet where repetitive logic is used for calculating the total price based on different shipping methods:
TypeScript1class Order { 2 items: Item[]; 3 tax: number; 4 5 constructor(items: Item[], tax: number) { 6 this.items = items; 7 this.tax = tax; 8 } 9 10 getItems(): Item[] { 11 return this.items; 12 } 13 14 getTax(): number { 15 return this.tax; 16 } 17} 18 19class Item { 20 price: number; 21 quantity: number; 22 23 constructor(price: number, quantity: number) { 24 this.price = price; 25 this.quantity = quantity; 26 } 27 28 getPrice(): number { 29 return this.price; 30 } 31 32 getQuantity(): number { 33 return this.quantity; 34 } 35} 36 37function calculateClickAndCollectTotal(order: Order): number { 38 let itemsTotal = 0; 39 for (let item of order.getItems()) { 40 itemsTotal += item.getPrice() * item.getQuantity(); 41 } 42 let shippingCost = itemsTotal > 100 ? 0 : 5; 43 return itemsTotal + shippingCost + order.getTax(); 44} 45 46function calculatePostShipmentTotal(order: Order, isExpress: boolean): number { 47 let itemsTotal = 0; 48 for (let item of order.getItems()) { 49 itemsTotal += item.getPrice() * item.getQuantity(); 50 } 51 let shippingCost = isExpress ? itemsTotal * 0.1 : itemsTotal * 0.05; 52 return itemsTotal + shippingCost + order.getTax(); 53}
Both methods 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 method, we can eliminate redundancy and streamline updates:
TypeScript1function calculateClickAndCollectTotal(order: Order): number { 2 let itemsTotal = calculateItemsTotal(order); 3 let shippingCost = itemsTotal > 100 ? 0 : 5; 4 return itemsTotal + shippingCost + order.getTax(); 5} 6 7function calculatePostShipmentTotal(order: Order, isExpress: boolean): number { 8 let itemsTotal = calculateItemsTotal(order); 9 let shippingCost = isExpress ? itemsTotal * 0.1 : itemsTotal * 0.05; 10 return itemsTotal + shippingCost + order.getTax(); 11} 12 13function calculateItemsTotal(order: Order): number { 14 let itemsTotal = 0; 15 for (let item of 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.
Let's look at another example dealing with repeated calculations for discount rates:
TypeScript1function applyDiscount(price: number, customer: Customer): number { 2 let loyaltyDiscount = customer.getLoyaltyLevel() * 0.02; 3 price *= (1 - loyaltyDiscount); 4 // Additional discounts 5 let 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:
TypeScript1function applyDiscount(price: number, customer: Customer): number { 2 const loyaltyDiscount = customer.getLoyaltyLevel() * 0.02; 3 const seasonalDiscount = 0.10; 4 5 const 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. 🎉
Our final example involves temporary variables that lead to repetition:
TypeScript1function isEligibleForDiscount(customer: Customer): boolean { 2 const newCustomer = customer.getSignUpDate().isAfter(new Date(Date.now() - 3 * 30 * 24 * 60 * 60 * 1000)); 3 return newCustomer && customer.getPurchaseHistory().length > 5; 4} 5 6function isEligibleForLoyaltyProgram(customer: Customer): boolean { 7 const newCustomer = customer.getSignUpDate().isAfter(new Date(Date.now() - 3 * 30 * 24 * 60 * 60 * 1000)); 8 return newCustomer || customer.getLoyaltyLevel() > 3; 9}
The variable newCustomer
is used in multiple places, causing duplicated logic.
Let's refactor by extracting the logic into a method, reducing duplication and enhancing modularity:
TypeScript1function isEligibleForDiscount(customer: Customer): boolean { 2 return isNewCustomer(customer) && customer.getPurchaseHistory().length > 5; 3} 4 5function isEligibleForLoyaltyProgram(customer: Customer): boolean { 6 return isNewCustomer(customer) || customer.getLoyaltyLevel() > 3; 7} 8 9function isNewCustomer(customer: Customer): boolean { 10 return customer.getSignUpDate().isAfter(new Date(Date.now() - 3 * 30 * 24 * 60 * 60 * 1000)); 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 Method, 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! 😊