ajidk

Posted on

# DRY “Don't Repeat Yourself”

DRY is a basic principle in any software development. Certainly, it is the most understandable software principle, but not everything is so obvious. I want to show you when you don’t need to follow this principle.

DRY is an acronym, of “Don’t Repeat Yourself”. The main problem that DRY can solve is a reducing repetition of code. Sometimes you need to have already existed function in another module, class, etc. And the easiest way to do that is just copy&paste this function.Congratulations, DRY principle violated. Factual copping of code creates for you one huge problem:

It is hard to maintain all these functions on the whole project, and if you need to change this function — you should change it in all places where did you copy it.

How to reduce DRY
the key points for how to apply abstraction to write code that doesn’t repeat itself:

• Create functions for common software patterns. We call them higher order function.
• Replace the boilerplate in your code with higher order funcitons.

Some examples of higher order functions include:

• map --- modifying each element in the array based on give rule
const finalParticipants = ["Taylor", "Donald", "Don"];

// add string after each final participant
const announcements = finalParticipants.map((member) => {
return member + " joined the contest.";
});

console.log(announcements);
// [
//   "Taylor joined the contest.",
//   "Donald joined the contest.",
//   "Don joined the contest.",
// ];
• filter --- getting subset of the array the passes a given criterion
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter((n) => {
return n > 5;
});
console.log(filteredArray); //[ 11, 42, 14, 39 ]
• reduce --- combining everything in the array based on a given rule

const arrayOfNumbers = [1, 2, 3, 4];

const sum = arrayOfNumbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
});

console.log(sum); // 10

• forEach --- executes a callback function on each of the elements in an array in order.
const numbers = [28, 77, 45];

numbers.forEach((number) => {
console.log(number);
// 28
// 77
// 45
});

• Maintainability
• Reuse
• Cost
• Testing