Introduction
Do you love coding but catch yourself writing the same code again and again? Have you ever paused and thought, “Isn’t there a more efficient way to handle this?”? Fortunately, there is a proven solution—the DRY (Don’t Repeat Yourself) Principle, a core concept that helps developers write cleaner, more maintainable code.
Rather than duplicating the same logic throughout the codebase, developers should define it once and reuse it wherever needed. This approach results in code that is:
Easier to maintain
Less prone to errors
More scalable
Cleaner and easier to read
Consider you are developing an application that calculates discounts for two customer types: Regular and Premium. Without applying the DRY principle, you might end up repeating the same or very similar logic in several different parts of the code.
Problem Without DRY
public class CustomerService
{
public double GetDiscountForRegularCustomer(double amount)
{
if (amount > 1000)
{
return amount * 0.10; // 10% discount
}
else
{
return amount * 0.05; // 5% discount
}
}
public double GetDiscountForPremiumCustomer(double amount)
{
if (amount > 1000)
{
return amount * 0.20; // 20% discount
}
else
{
return amount * 0.10; // 10% discount
}
}
}In this case, the discount calculation logic is duplicated with minor differences. If the business rules change, you would have to modify several methods, which increases the chances of inconsistencies and errors.
Applying DRY Principle
Let’s improve the code by applying the DRY principle and moving the shared logic into a single, reusable method.
Move the common logic into DiscountService, where the discount amount is calculated based on the provided parameters, while CustomerService simply passes the required parameters to perform the calculation.
public class DiscountService
{
public double CalculateDiscount(double amount, double highAmountRate, double lowAmountRate)
{
if (amount > 1000)
{
return amount * highAmountRate;
}
else
{
return amount * lowAmountRate;
}
}
}
public class CustomerService
{
private readonly DiscountService _discountService = new DiscountService();
public double GetRegularCustomerDiscount(double amount)
{
return _discountService.CalculateDiscount(amount, 0.10, 0.05);
}
public double GetPremiumCustomerDiscount(double amount)
{
return _discountService.CalculateDiscount(amount, 0.20, 0.10);
}
}
Join the conversation! Your thoughts help the community grow.