What is DRY Code
"Don't repeat yourself" (DRY) is a principle of software development aimed at reducing repetition of software patterns,[1] replacing it with abstractions or using data normalization to avoid redundancy.
The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system".It usually means refactoring code by taking something done several times and turning it into a loop or a function. DRY code is easy to change, because you only have to make any change in one place.
Examples of Non-DRY and Dry Code
let drinks = ['lemonade', 'soda', 'tea', 'water'];
let food = ['beans', 'chicken', 'rice'];
//non DRY code
console.log(drinks[0]);
console.log(drinks[1]);
console.log(drinks[2]);
console.log(drinks[3]);
console.log(food[0]);
console.log(food[1]);
console.log(food[2]);
// DRY code
function logItems (array) {
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
}
logItems(drinks);
logItems(food);
CONCLUSION
Whenever you finish writing some code, you should always look back to see if there is any way you can DRY it up, including:using descriptive variable names, taking repetitive bits of code and extracting them into a function or loop.
Connect me on facebook
Top comments (7)
Loved it! But be careful, as this community have some DRY detractors lurking in the shadows, trying to make you think it is sometimes OK to repeat code or data. 😄
Well... as anything in life nothing is just BLACK or WHITE. Yes, don't repeat your self (specially if is pure copy paste code), but think somewhere between DRY and WET (write everything twice). Sometimes two things that are almost the same and could be abstracted are not worth the effort, and let them be give them flexibility ahead... maybe they are complex, or maybe they are simple enough that it's not worth creating interfaces and x mpre files to abstract them. 😉 Use good judgement! And if you see something similar 3 times, then YES refactor.
Hello! You are late to the big discussions we had. Long story short, it got heated, I was insulted, but in the end I was able to provide reasoning against WET every single time. Let's not go down this road again. 😄
Let's just agree to disagree.
Deal! Just wanted to point out that there is some flexibility on everything 😉
Sorry you were insulted! That's never a constructive discussion.
😆😆😆
Sure
I thought you had to dry your code in sunlight or something. Thanks for explaination