Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: June 17, 2023
In this tutorial, we’ll learn about the DRY software design principle.
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.
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.
The advantages of the DRY principle include the following:
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.
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.
In this short article, we learned about the DRY software principle and its advantages.