skip to content
Home Image
Table of Contents

DRY (Don’t Repeat YourSelf)

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.

function greetStudent(name) {
console.log("Hello " + name + "!");
console.log("Welcome to our school!");
console.log("Have a great day " + name + "!");
}
function greetTeacher(name) {
console.log("Hello " + name + "!");
console.log("Welcome to our school!");
console.log("Have a great day " + name + "!");
}
//logic repeated for same task
greetStudent("User");
greetTeacher("Mr User");
//apply DRY Principle
function printGreeting(name) {
console.log(`Hello ${name}!`);
console.log("Welcome to our school!");
console.log(`Have a great day ${name}!`);
}
printGreeting("User");
printGreeting("Mr User");

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

4. Advantages of DRY

The advantages of the DRY principle include the following:

a. 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

b. 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.

WET (Write Everything Twice / We Enjoy Typing)

Definition: The counter-principle to DRY.

Context: Sometimes, applying DRY too early leads to “Premature Abstraction.”

The Rule of Thumb: It is often better to duplicate code twice than to create the wrong abstraction. Usually, developers wait until the third time a piece of code is repeated before abstracting it.

Why? If two pieces of code look similar but change for different business reasons, combining them creates “accidental coupling.” WET acknowledges that some repetition is acceptable to keep code independent.