Sobes.tech
Junior

What do you know about the principles of DRY programming?

sobes.tech AI

Answer from AI

DRY is an acronym for "Don't Repeat Yourself".

The DRY principle is about avoiding duplication of code and information in a system. Each piece of information should have a single, unambiguous representation.

Applying DRY:

  • Improves maintainability: changes need to be made in only one place.
  • Reduces the likelihood of errors: when one logic is changed, there's no risk of forgetting to update its copy.
  • Makes the code more readable and understandable.

Examples of DRY violations and their fixes:

  • Logic duplication in functions:

    # Bad: discount calculation logic is repeated
    def calculate_price_product_a(price):
        discount = price * 0.1
        return price - discount
    
    def calculate_price_product_b(price):
        discount = price * 0.1
        return price - discount
    
    # Good: logic extracted into a separate function
    def calculate_discounted_price(price, discount_rate):
        return price * (1 - discount_rate)
    
    def calculate_price_product_a(price):
        return calculate_discounted_price(price, 0.1)
    
    def calculate_price_product_b(price):
        return calculate_discounted_price(price, 0.1)
    
  • Duplication of strings or constants:

    # Bad: error message is repeated
    print("Error: Invalid input data.")
    raise ValueError("Error: Invalid input data.")
    
    # Good: constant for error message
    ERROR_MESSAGE = "Error: Invalid input data."
    print(ERROR_MESSAGE)
    raise ValueError(ERROR_MESSAGE)
    
  • Duplication of data structures: Using the same structure (e.g., a dictionary with the same keys) in different parts of the code instead of defining it once.

Comparison with other principles:

Principle Description Connection with DRY
KISS (Keep It Simple, Stupid) Keep things simple. DRY supports KISS by eliminating complexity caused by duplication.
YAGNI (You Aren't Gonna Need It) Don't add functionality until needed. YAGNI prevents creating duplicate functionality, supporting DRY.

It's important to note that excessive application of DRY can lead to over-abstraction and code complexity (Violate DRY Principle, or VDRY). One should not create generalized solutions for cases unlikely to recur. The key is a reasonable balance.