The DRY Principle

The DRY Principle

Jan 05, 2021

DRY (Don’t Repeat Yourself) is a principle of software development - and more like a guideline, I would say. The focus is to avoid repetition of information. The rationale is that you increase the maintainability of the code by only having to modify it in one place. Functions are very interesting solutions when considering the application of the DRY principle. Take a look at the repetition of code below:

temp = 55
new_temp = ((temp - 32) * (5 / 9)) + 273.15

temp2 = 46 
new_temp_k = ((temp2 - 32) * (5 / 9)) + 273.15

For every new temp, the code right below it would have to be duplicated to acommodate a new temp (temp2, for example) variable. You are basically duplicating code because of just one variable change, from temp to temp2. That violates DRY. The solution:

temp = 55
new_temp = fahr_to_kelvin(fahr = temp)

temp2 = 46 
new_temp_k = fahr_to_kelvin(fahr = temp2)

The function holds the calculation to convert fahrenheit to kelvin and because that calculation is centralized now in a function, there is no repetition of code anymore. If changes are needed, they will happen only in one place: inside the function.

def fahr_to_kelvin(fahr) 
    """Convert temperature in Fahrenheit to kelvin.

    Parameters:
    -----------
    fahr: int or float
        The temperature in Fahrenheit.
    
    Returns:
    -----------
    kelvin : int or float
        The temperature in kelvin.
    """
    kelvin = ((fahr - 32) * (5 / 9)) + 273.15
    return kelvin

It is worth noting that the function is grouping the lines relating to the convertion of temperatures. Both lines refer to the same concept/activity/idea/functionality and that is why they are grouped together in a function. DRY is not about abstracting unrelated lines/groups of functionality. One needs to be careful with that.

Resources:

https://www.earthdatascience.org/courses/intro-to-earth-data-science/write-efficient-python-code/intro-to-clean-code/dry-modular-code/

https://stackoverflow.com/questions/55497672/dry-principle-in-python-init-method

https://scientificallysound.org/2018/07/19/python-functions/

https://dzone.com/articles/10-coding-principles-every-programmer-should-learn

Enjoy this post?

Buy fmachs a book

More from fmachs