1. Overview

In this tutorial, we’ll learn about the DRY software design principle.

2. Definition

DRY stands for Don’t Repeat Yourself. It’s a software development principle with the goal of removing logic duplication.

DRY was first introduced in the book The Pragmatic Programmer and ensures that a particular logic appears only once in the codebase.

3. An Example

For example, writing a function that contains a specific logic and then calling it multiple times in our code is a form of applying the DRY principle.

Here is a pseudocode that receives two temperatures in Fahrenheit and converts them into Celsius before applying DRY:

algorithm ConvertTemperaturesBeforeDRY(fah1, fah2):
    // INPUT
    //   fah1, fah2 = two temperatures in Fahrenheit degrees
    // OUTPUT
    //   Prints the equivalent temperatures in Celsius degrees

    cel1 <- (fah1 - 32) * 5 / 9
    cel2 <- (fah2 - 32) * 5 / 9

    print cel1
    print cel2

Now here is the same program after applying DRY:

algorithm ConvertTemperaturesAfterDRY(fah1, fah2):
    // INPUT
    //   fah1, fah2 = Two temperatures in Fahrenheit
    // OUTPUT
    //   Prints the equivalent temperatures in Celsius

    cel1 <- fahrenheitToCelsius(fah1)
    cel2 <- fahrenheitToCelsius(fah2)

    print cel1
    print cel2

function fahrenheitToCelsius(fah):
    // Converts Fahrenheit to Celsius
    return (fah - 32) * 5 / 9

We can see that, after applying DRY, the logic that converts Fahrenheit to Celsius appears only once in our code.

4. Advantages of DRY

The advantages of the DRY principle include the following:

  • It makes the codebase easier to maintain since if we wanted to change the logic or add to it, we’d only need to change it in one place instead of multiple locations where the logic appears
  • It makes the code easier to read because there’ll be less redundancy in the code

It’s important to mention that misusing DRY (creating functions where we don’t need to, making unnecessary abstractions, and so on) can lead to more complexity in our code rather than simplicity.

5. The Opposite of DRY

WET (which can stand for We Enjoy Typing, Write Every Time, and Waste Everyone’s Time) is when we write the same logic more than once in our code, violating the DRY principle. As a result, the code becomes more difficult to read. Furthermore, if we wanted to change the logic, we’d have to make changes to all of its appearances in our codebase, making the code harder to maintain.

6. Summary

In this short article, we learned about the DRY software principle and its advantages.

Comments are closed on this article!